2010-10-27 34 views
0

我期待學習如何構建一些檢測按鍵以抑制功能的東西。jQuery - 基於最後一次按鍵限制服務器命中?

喜歡的東西:

var LastKeyPress; 
function hitTheServer() { 
if LastKeyPress > 2 seconds ago { 
    hit the server and do stuff 
    LastKeyPress = now(); 
} 
} 

你覺得呢?也許這是內置於jQuery?此外,它可能會用於許多功能,並且在全球範圍內使用它可能會很有趣,所以我可以使用較少的代碼並應用於多種功能。思考?

感謝

回答

1

我會說,像這樣:

var LastKeyPress; 
function hitTheServer(){ 
    n = new Date().getSeconds(); 
    if (LastKeyPress == undefined || LastKeyPress > n+2){ 

     //Code 

     LastKeyPress = n; 
    } 
} 
+0

有趣的想法。問題是基於秒。所以如果用戶長時間停頓,它會失敗。我認爲它應該是基於時間的,而不是第二基於的。另外我認爲上面有一個錯誤。似乎沒有在我的測試中工作? – AnApprentice 2010-10-28 04:27:29

0

這是使用window.setTimeout相對簡單:

// Example function to be throttled 
function throttledFunction() { 
    alert("Two seconds since last keypress"); 
} 

var keypressTimer = null, keypressDelay = 2000; 

document.onkeypress = function() { 
    if (keypressTimer) { 
     window.clearTimeout(keypressTimer); 
    } 
    keypressTimer = window.setTimeout(function() { 
     keypressTimer = null; 
     throttledFunction(); 
    }, keypressDelay); 
};