Run javascript function when user finishes typing instead of on key up?

前端 未结 29 2442
我寻月下人不归
我寻月下人不归 2020-11-22 04:03

I want to trigger an ajax request when the user has finished typing in a text box. I don\'t want it to run the function on every time the user types a letter because that wo

29条回答
  •  时光取名叫无心
    2020-11-22 04:38

    Modifying the accepted answer to handle additional cases such as paste:

    //setup before functions
    var typingTimer;                //timer identifier
    var doneTypingInterval = 2000;  //time in ms, 2 second for example
    var $input = $('#myInput');
    
    // updated events 
    $input.on('input propertychange paste', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(doneTyping, doneTypingInterval);      
    });
    
    //user is "finished typing," do something
    function doneTyping () {
      //do something
    }
    

提交回复
热议问题