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

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

    I just figured out a simple code to wait for user to finish typing:

    step 1.set time out to null then clear the current timeout when the user is typing.

    step 2.trigger clear timeout to the variable define before keyup event is triggered.

    step 3.define timeout to the variable declared above;

    
    

    javascript code

    var textInput = document.getElementById('input');
    var textdata = document.querySelector('.data');
    // Init a timeout variable to be used below
    var timefired = null;
    
    // Listen for keystroke events
    // Init a timeout variable to be used below
    var timefired = null;// Listen for keystroke events
    textInput.onkeyup = function (event) {
    clearTimeout(timefired);
    timefired = setTimeout(function () {
        textdata.innerHTML = 'Input Value:'+ textInput.value;
      }, 600);
    };
    

提交回复
热议问题