-
Notifications
You must be signed in to change notification settings - Fork 0
throttle.js
Manabu Yasuda edited this page May 10, 2016
·
1 revision
スクロールなどのイベントを任意の時間の間隔で実行します。
/**
* @desc - 関数などのイベントを任意の時間が経つたびに実行します。
* @link - http://scn.sap.com/community/labs/blog/2014/04/30/debounce-and-throttle-in-javascript
* @example
* $(window).on('scroll', throttle(function() {
* func();
* }, 300));
*/
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};