防抖和節流是對應的:app
防抖是規定時間內觸發就一直延遲,直到規定時間內不觸發了就執行最後一次事件;dom
節流是執行第一次,在規定時間內不會再次觸發,過了規定時間就會再次觸發的。函數
function debounce(fn, wait) {this
var timeout = null;//每次執行函數的時候若是上次沒有執行完成就從新賦值spa
return function() {事件
if(timeout !== null)rem
clearTimeout(timeout);//若是以前有定時器的話就清除定時器it
timeout = setTimeout(fn, wait);//每次觸發都從新執行定時器io
}console
}
// 處理函數
function handle() {
console.log(Math.random());
}
// 滾動事件
window.addEventListener('scroll', debounce(handle, 1000));
時間戳方案
var throttle = function(func, delay) {
var prev = Date.now();
return function() {
var context = this;
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
func.apply(context, args);
prev = Date.now();
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
定時器方案
var throttle = function(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
時間戳+定時器
var throttle = function(func, delay) {
var timer = null;
var startTime = Date.now();
return function() {
var curTime = Date.now();
var remaining = delay - (curTime - startTime);
var context = this;
var args = arguments;
clearTimeout(timer);
if (remaining <= 0) {
func.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(func, remaining);
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));