您可以通過調用setTimeout
呼叫的形式創建一些滯後來完成此操作。這是對可能重複觸發的昂貴操作的典型響應。當發生keyup
時,爲100ms(例如)計劃一個超時。如果在該100ms內發生另一個keyup
,則取消先前的超時並設置一個新的超時。發生超時時,請執行昂貴的操作。
例如,如果你以前的處理程序是這樣的:
function handleKeyUp() {
doThisExpensiveThing();
doThatExpensiveThing();
doAnotherExpensiveThing();
}
...您的新的可能是這樣的:
var keyupTimer = 0; // 0 is a safe "no timer" value, setTimeout never returns 0
function handleKeyUp() {
// Have an outstanding call?
if (keyupTimer) {
// Yes, clear it
clearTimeout(keyupTimer);
}
// Set a new call to occur in 100ms
keyupTimer = setTimeout(doExpensiveStuff, 100);
}
function doExpensiveStuff() {
// Clear the timer handle so we know we don't have a call pending
keyupTimer = 0;
// Do the expensive stuff
doThisExpensiveThing();
doThatExpensiveThing();
doAnotherExpensiveThing();
}
@Jimmy:我想我會把它作爲讀者的練習。 :-)你應該可以直接應用上面的內容。 –
ok thanx T.J.Crowder – Jimmy