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

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

    Multiple timers per page

    All the other answers only work for one control (my other answer included). If you have multiple controls per page (e.g. in a shopping cart) only the last control where the user typed something will get called. In my case this is certainly not the wished behaviour - each control should have its own timer.

    To solve this, you simply have to pass an ID to the function and maintain a timeoutHandles dictionary as in the following code:

    Function Declaration:

    var delayUserInput = (function () {
        var timeoutHandles = {};    
        return function (id, callback, ms) {        
            if (timeoutHandles[id]) {
                clearTimeout(timeoutHandles[id]);
            }
    
            timeoutHandles[id] = setTimeout(callback, ms);             
        };
    })();
    

    Function Usage:

      delayUserInput('yourID', function () {
         //do some stuff
      }, 1000);
    

提交回复
热议问题