我建議這是一個通用的解決方案:
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