Javascript jQuery-基于最后一次按键限制服务器点击?
我希望学习如何构建一些能够检测按键的功能,以限制功能 比如:Javascript jQuery-基于最后一次按键限制服务器点击?,javascript,jquery,timer,Javascript,Jquery,Timer,我希望学习如何构建一些能够检测按键的功能,以限制功能 比如: var LastKeyPress; function hitTheServer() { if LastKeyPress > 2 seconds ago { hit the server and do stuff LastKeyPress = now(); } } 你觉得怎么样?也许这是jQuery内置的?而且,我可能会在很多函数中使用它,让它在全局范围内工作可能会很有趣,这样我就可以使用更少的代码并应用于多个
var LastKeyPress;
function hitTheServer() {
if LastKeyPress > 2 seconds ago {
hit the server and do stuff
LastKeyPress = now();
}
}
你觉得怎么样?也许这是jQuery内置的?而且,我可能会在很多函数中使用它,让它在全局范围内工作可能会很有趣,这样我就可以使用更少的代码并应用于多个函数。想法
谢谢我想说:
var LastKeyPress;
function hitTheServer(){
n = new Date().getSeconds();
if (LastKeyPress == undefined || LastKeyPress > n+2){
//Code
LastKeyPress = n;
}
}
您可以使用
窗口签出这相对简单。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);
};
好主意。问题是它是以秒为基础的。因此,如果用户长时间暂停,它就会失败。我认为它应该是以时间为基础的,而不是以秒为基础的。我还认为上面的代码有一个bug。在我的测试中似乎不起作用?