参考https://www.cnblogs.com/momo798/p/9177767.html
一句话总结:防抖是碰到新调用就重置计时器,节流是碰到新调用就无视
1.防抖
1.1解释
函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。如下图,持续触发scroll事件时,并不执行handle函数,当1000毫秒内没有触发scroll事件时,才会延时触发scroll事件。
1.2实现
使用settimeout实现,触发事件,若当前没有定时器,设定定时器。若有定时器,重设定时器。
function debounce(fn, wait){
var timeout = null;
return function () {
console.log("debounce")
if(timeout!==null) clearTimeout(timeout);
timeout=setTimeout(fn, wait);
}
}
function handler(){
var node = document.createElement('h3');
var textnode = document.createTextNode('test');
node.appendChild(textnode);
document.body.appendChild(node);
console.log("called")
}
document.getElementById('divx').addEventListener('click',debounce(handler,1000))
2.节流
2.1解释
当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
2.2实现
使用settimeout实现,若当前没有定时器,设定定时器。若有定时器,无视。
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());
}
document.getElementById('divx').addEventListener('click',throttle(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());
}
document.getElementById('divx').addEventListener('click',throttle(handle,1000))