0
<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>       
ses
  • 13,174
  • 31
  • 123
  • 226

1 Answers1

6

You're calling the function immediately and passing its result (undefined) to setTimeout(). You need to pass a function reference to setTimeout(), which in this case you'd do by removing the parentheses after doneTyping:

typingTimer = setTimeout(doneTyping, doneTypingInterval);

Or (not applicable to your example but for future reference), if you needed to call a function with some arguments, say you wanted to call doneTyping('test') after the specified interval, you could wrap that in an anonymous function expression:

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

ONLINE DEMO

P.S. Indirectly related to what you're asking, I'd suggest also moving the clearTimeout() into the keyup handler, just before setTimeout(), and removing the keydown handler, something like this, otherwise you may find you have two or more timeouts set at once because to type an uppercase letter the sequence is (1) shift down (2) letter down (3) letter up (4) shift up. Also even without using the shift key, when typing quickly I often find I haven't quite released a key before typing the next letter so I get more than one keydown event in a row before the corresponding keyup events - this has no noticeable bad effect in normal circumstances, but is noticeable when there's code responding to both the down and up events.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241