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

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

    The chosen answer above does not work.

    Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.

    The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.

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

    And the same code in vanilla JavaScript solution:

    //setup before functions
    let typingTimer;                //timer identifier
    let doneTypingInterval = 5000;  //time in ms (5 seconds)
    let myInput = document.getElementById('myInput');
    
    //on keyup, start the countdown
    myInput.addEventListener('keyup', () => {
        clearTimeout(typingTimer);
        if (myInput.value) {
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        }
    });
    
    //user is "finished typing," do something
    function doneTyping () {
        //do something
    }
    

    This solution does use ES6 but it's not necessary here. Just replace let with var and the arrow function with a regular function.

提交回复
热议问题