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

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

    I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, i.e. if you type "Hello" really quickly; instead of firing just once when you stop typing, the function would fire 5 times.

    The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set. See below:

    //setup before functions
    var typingTimer;                //timer identifier
    var doneTypingInterval = 5000;  //time in ms, 5 second for example
    
    //on keyup, start the countdown
    $('#myInput').on("keyup", function(){
        if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    });
    
    //on keydown, clear the countdown 
    $('#myInput').on("keydown", function(){
        clearTimeout(typingTimer);
    });
    
    //user is "finished typing," do something
    function doneTyping () {
        //do something
    }
    

    N.B. I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation. Sorry!

提交回复
热议问题