This question already has answers here:
setTimeout ignores timeout? (Fires immediately) [duplicate]
                                
                                    (3个答案)
                                
                        
                6年前关闭。
            
        

<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>

最佳答案

您正在立即调用该函数并将其结果(未定义)传递给setTimeout()。您需要将函数引用传递给setTimeout(),在这种情况下,您可以通过删除doneTyping之后的括号来实现:

typingTimer = setTimeout(doneTyping, doneTypingInterval);


或者(不适用于您的示例,但仅供以后参考),如果您需要使用一些参数来调用函数,例如您想在指定的间隔后调用doneTyping('test'),则可以将其包装在匿名函数表达式中:

typingTimer = setTimeout(function() { doneTyping('test'); }, doneTypingInterval);


ONLINE DEMO

附言与您的要求间接相关,我建议您也将clearTimeout()移到keyup处理程序中,在setTimeout()之前,并删除keydown处理程序something like this,否则您可能会发现自己有一次设置两个或更多超时,因为键入大写字母的顺序是(1)下移(2)下字母(3)上移(4)上移。另外,即使不使用Shift键,在快速键入时,我经常会发现在键入下一个字母之前我还没有完全释放键,因此在对应的keydown事件之前,我连续获得了多个keyup事件-在正常情况下,不会有明显的不良影响,但是当代码同时对down和up事件做出响应时,这种影响是显而易见的。

关于javascript - 为什么javascript在键入时会立即发送事件,但延迟5秒后才发送? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17630043/

10-09 18:05
查看更多