我建议这是一个通用的解决方案:
function sleep (ms, args, obj) {
/* Called at the top of a function to invoke a delay in processing that
function
Returns true if the function should be executed, and false if the sleep
timer is activated.
At the end of the sleep tiemout, the calling function is re-called by
calling it with "apply (obj, args || [])".
*/
var caller = sleep.caller;
if (caller.sleepTimer) {
/* if invoked from timeout function, delete timer and return false */
delete caller.sleepTimer;
return true;
}
/* Create timer and re-call caller at expiry */
caller.sleepTimer = window.setTimeout (function() {
caller.apply (obj || null, args || []);
},ms);
return false;
}
使用的例子:
function delayed() {
if (!sleep (5000)) return;
document.body.innerHTML += "<p>delayed processing</p>";
}
function delayed_args (a, b) {
if (!sleep (10000, arguments)) return;
document.body.innerHTML += "<p>args : (" + a + ", " + b + ")</p>";
}
function delayed_method_args (a,b) {
if (!sleep (20000, arguments, this)) return;
document.body.innerHTML += "<p>method_args " + this + " (" + a + ", " + b + ")</p>";
}
测试在Opera和Firefox 3.0
来源
2009-06-24 07:28:19
HBP
睡在JavaScript是一个糟糕的主意,因为它会导致浏览器的用户界面变得无法响应 – cobbal 2009-06-24 06:04:56
我担心会做十秒的验证。那时是服务器响应的时间吗?如果您使用ajax调用进行验证,那么您是否应该获得回调? – Nosredna 2009-06-24 06:12:08