1cco
10/5/2017 - 11:00 AM

throttle and debounce

イベントの間引き処理。どちらもイベントハンドラとして動作する。throttleは連続して発生するイベントで一定時間経過後に継続的に実行される。debounceは連続して発生するイベントが一定時間経過後も発生しなければ実行される。 ウィンドウのリサイズイベントなら、throttleはリサイズしている間、一定時間ごとに実行。debounceはリサイズをやめたら実行。


var debounce = (function() {
	var interval = 500;
	var timer;
	return function() {
		clearTimeout(timer);
		timer = setTimeout(function() {
			//Your Code Here.
		}, interval);
	};
})();

window.addEventListener('resize', debounce);
var throttle = (function() {
	var interval = 500;
	var lastTime = new Date().getTime() - interval;
	return function() {
		if (lastTime + interval <= new Date().getTime()) {
			lastTime = new Date().getTime();
			//Your Code Here.
		}
	};
})();

window.addEventListener('resize', throttle);
var debounce = function(callback, interval) {
	var timer;
	return function() {
		clearTimeout(timer);
		timer = setTimeout(function() {
			callback.call();
		}, interval);
	};
};
var throttle = function(callback, interval) {
	var lastTime = Date.now() - interval;
	return function() {
		if (lastTime + interval <= Date.now()) {
			lastTime = Date.now();
			callback.call();
		}
	};
};

window.addEventListener('scroll', debounce(function(){
	//Your code here
}, 2000));
window.addEventListener('scroll', throttle(function(){
	//Your code here
}, 1000));