zoxon
9/1/2015 - 2:19 AM

debounce.js

/**
	 * @param  {function} func      the code to be executed
	 * @param  {int+} threshold     delay after trigger event (in milliseconds)
	 * @param  {boolean} execAsap   forces to execute the code as soon as possible
	 * @return {void}
	 *
	 * @author Paul Irish
	 * @see http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
	 */
	var debounce = function (func, threshold, execAsap) {
		var timeout;

		return function () {
			var obj = this, args = arguments;
			function delayed () {
				if (!execAsap)
					func.apply(obj, args);
				timeout = null;
			}

			if (timeout)
				clearTimeout(timeout);
			else if (execAsap)
				func.apply(obj, args);

			timeout = setTimeout(delayed, threshold || 100);
		};
	};