函数防抖节流原文地址:https://www.cnblogs.com/youma/p/10559331.html
函数防抖
当持续事件发生时,一定时间内没有触发事件,时间函数才会执行一次,如果在规定的时间内,再次触发了该事件,则重新计时。也就是说,用户在规定时间内多次请求,最后只执行一次。
函数防抖
function debounce(fn, wait) {
//设置 timeout
var timeout = null;
return function () {
//如果 timeout 不等于 null
if (timeout !== null) {
//清除原来的定时器
clearTimeout(timeout);
//重新赋值
timeout = setTimeout(fn, wait)
}else {
//如果 timeout 等于 null,执行该函数
timeout = setTimeout(fn, wait)
}
}
}
// 处理函数
function handle() {
console.log(Math.random());
}
// 滚动事件 传入handle函数
window.addEventListener('scroll', debounce(handle, 1000));
注意:在阅读代码时发现debounce(handle, 1000) 返回的时候是一个函数会自动执行。
我总结了三种触发情况
情况一、 通过引入传递函数的时候,会自动调用返回的函数
function fns1(){
return function () {
console.log('执行1111111')
alert('dinji')
}
}
document.body.addEventListener('click', fns1(), false);
//情况二、能够正常执行
document.body.addEventListener('click', function () {
console.log(7777)
}, false);
//情况三、不会正常执行
document.body.addEventListener('click', function () {
return function () {
console.log(666)
}
}, false);
函数节流
当持续事件发生,保证事件在一定时间内之调用一次。 函数防抖和节流的区别: 防抖时多次执行变一次,节流是多次执行变每隔一段事件执行
var throttle = function(func, delay) {
var prev = Date.now(); //获取时间戳
return function() {
var context = this; //this指向window
var args = arguments; //获取参数
var now = Date.now(); //获取时间戳
if (now - prev >= delay) { //如果两个时间戳相减大于规定时间 则执行
func.apply(context, args); //改变方法的this指向,并拆地参数
prev = Date.now();
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
这个节流函数利用时间戳让第一次滚动事件执行一次回调函数,此后每隔1000ms执行一次,在小于1000ms这段时间内的滚动是不执行的
利用定时器:每隔一秒触发一次
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));