简体   繁体   中英

Cancel Debounce Function

I have the following debounce function and I need to be able to cancel the debounce by calling clearTimeout(timeout); within the scope of the debounce function. I cannot use a library for this.

Here is my code:

var utils = (function(){
    return {
        debounce: function(func, wait, immediate){
          var timeout;
            return function() {
                var context = this, args = arguments;
                var later = function() {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        }
    }
})();

I want to be able to do something like this but again I cannot figure it out.

var deb = utils.debounce(function(){ console.log("do something"); }, 500);

$(document).on('keyup', '#myId', deb);

deb.cancel(); //this cancel call clears the timeout variable in the debounce function. 

Add the cancel function as a property to the returned function:

const utils = (function(){
  return {
    debounce: function(func, wait, immediate) {
      let timeout;
      const fn = function() {
        const context = this, args = arguments;
        const later = function() {
          timeout = null;
          if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
      };
      return Object.assign(fn, {
        clear() { clearTimeout(timeout); }
      });
    }
  }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM