debounce + throttle

facebook

by Paco86

JavaScript

/* debounce: only execute last event */
var debounce = function(fn, delay) {
  var timeoutId;
  return function() {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
    	fn.apply(this, arguments);
      timeoutId = null;
    }, delay);
  }
}

/* throttle: only execute first event */
var throttle = function(fn, delay) {
  var timeoutId;
  return function() {
    if (timeoutId) return;
    timeoutId = setTimeout(() => {
    	fn.apply(this, arguments);
      timeoutId = null;
    }, delay);
  }
}

/* throttle: execute all events, solwly */
var throttle2 = function(fn, delay) {
	var intervalId;
  var events = [];
	return function(...args) {
    events.push({ fn, args });
    if (intervalId) return;
  	intervalId = setInterval(() => {
    	var fnObj = events.shift();
      fnObj.fn.apply(this, fnObj.args);
      if (events.length <= 0) {
      	clearInterval(intervalId);
      }
    }, delay);
  }
}

/* throttle: execute all events, solwly */
var throttle2 = function(fn, delay) {
  var intervalId;
  var events = [];
  return function() {
    events.push({ fn, arguments });
    if (intervalId) return;
    intervalId = setInterval(() => {
    	if (events.length) {
      	var { fn, arguments } = events.shift();
      	fn.apply(this, arguments);
				if (events.length === 0) intervalId = null;
      }
    }, delay);
  }
}


var consoleText = {
	myName: 'paco',
	logName: function(type) {
  	console.log(type + ' ' + this.name);
  }
}

var debounceFn = debounce(consoleText.logName, 1000);
var throttleFn = throttle(consoleText.logName, 4000);

debounceFn('debounceFn hi');
debounceFn('debounceFn hello');
throttleFn('throttleFn hi');
throttleFn('throttleFn hello1');
throttleFn('throttleFn hello2');
throttleFn('throttleFn hello3');
throttleFn('throttleFn hello4');