2010-10-27 24 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); 
};