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

前端 未结 29 2461
我寻月下人不归
我寻月下人不归 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:54

    agree with the @going 's answer. Another similar solution that worked for me is the one below. The only difference is that I am using .on("input"...) instead of keyup. This only captures changes in the input. other keys like Ctrl, Shift etc. are ignored

    var typingTimer;                //timer identifier
    var doneTypingInterval = 5000;  //time in ms (5 seconds)
    
    //on input change, start the countdown
    
    $('#myInput').on("input", function() {    
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function(){
            // doSomething...
        }, doneTypingInterval);
    });
    

提交回复
热议问题