Call a javascript function after 5 sec of last key press

前端 未结 3 619
-上瘾入骨i
-上瘾入骨i 2020-12-08 01:03

I have a form with an and I want to call a javascript function after 5 seconds of the last key press, and every time a new key is pres

相关标签:
3条回答
  • 2020-12-08 01:32

    Although it doesn't use jQuery, you could also have a look at the debouncing function described here.

    Steve

    0 讨论(0)
  • 2020-12-08 01:33

    Something like this should get you started:

    var timeout;
    $('input[type=text]').keypress(function() {
        if(timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
    
        timeout = setTimeout(myFunction, 5000)
    })
    
    0 讨论(0)
  • 2020-12-08 01:34

    This answer is great, but remember that you need to enable this code after the documents loads and after the function loads to clear the timeout.

    Here is the complete code:

    var timeout;
        $(document).ready(function(){
          $('input[type=text]').keypress(function() {
              if(timeout) {
                  clearTimeout(timeout);
                  timeout = null;
              }
              timeout = setTimeout(myFunction, 5000);
          });
        });
    		
    	var myFunction = new function() { 
    	  alert('myFunction is running');
    	  clearTimeout(timeout); // this way will not run infinitely
    	}
    		
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

    0 讨论(0)
提交回复
热议问题