<html>
<head>
<script src="jquery-1.9.0.min.js" type="text/javascript"></script>
</head>
<body>
<input id="input" type="text"/>
<script>
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#input').keyup(function(){
typingTimer = setTimeout(doneTyping(), doneTypingInterval);
});
//on keydown, clear the countdown
$('#input').keydown(function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
alert("123") // I get this alert immidiatelly when typing, but not after 5 sec dalay
}
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
您正在立即调用该函数并将其结果(未定义)传递给setTimeout().您需要传递一个函数引用setTimeout(),在这种情况下,您可以通过删除括号后执行doneTyping:
typingTimer = setTimeout(doneTyping, doneTypingInterval);
Run Code Online (Sandbox Code Playgroud)
或者(不适用于您的示例,但供将来参考),如果您需要使用某些参数调用函数,比如说您想doneTyping('test')在指定的时间间隔后调用,则可以将其包装在匿名函数表达式中:
typingTimer = setTimeout(function() { doneTyping('test'); }, doneTypingInterval);
Run Code Online (Sandbox Code Playgroud)
PS间接地与你问的内容有关,我建议你也可以在之前移动clearTimeout()到keyup处理程序中,然后setTimeout()移除keydown处理程序,就像这样,否则你可能会发现你有两个或更多的超时设置,因为键入一个大写字母的顺序是(1)向下移位(2)向下移位(3)向上移位(4)向上移位.即使不使用shift键,当快速键入时我经常发现在键入下一个字母之前我还没有完全释放键,所以我keydown在相应的keyup事件之前连续发生了多个事件 - 这在正常情况下没有明显的不良影响情况,但是当代码响应向下和向上事件时是明显的.
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |