Throttle & Debounce

by asdf

JavaScript

function debounce(func, wait) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			func.apply(context, args);
		};
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
	};
};
function write() {
	console.log('Func called');
}
//var debounced = debounce(write, 3000);
//document.addEventListener('click', debounced);

function throttle(func, wait) {
	var scheduled = false;
  var lastCall;
	return function() {
		var context = this, args = arguments;
    var now = +new Date();
		var later = function() {
			scheduled = false;
      lastCall = +new Date();
			func.apply(context, args);
		};
    
    if (now - lastCall >= wait) {
      lastCall = +new Date();
    	func.apply(context, args);
    } else if (!scheduled) {
    	scheduled = true;
      setTimeout(later, wait - (now - lastCall));
    }
	};
};
var throttled = throttle(write, 3000);
document.addEventListener('click', throttled);