- 函数防抖是:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
- 函数节流是:高频事件触发,但在n秒内只会执行一次,节流会稀释函数的执行频率
防抖
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
<title>debounce</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="debounce.js"></script>
</body>
</html>
function debounce(fn,time){
let timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this,arguments); //将 this 指向正确的对象(否则指向window),此处正确的对象为box
}, time);
}
}
function sayhi(){
console.log("hello lin");
}
let box = document.getElementById('box');
box.addEventListener('click',debounce(sayhi,2000));
节流
function throttle(fn,time){
let flag = true;
return function(){
if(!flag) return;
flag = false;
setTimeout(() => {
fn.apply(this,arguments);
flag = true;
}, time);
}
}
function sayhi(){
console.log("hello li");
}
let box = document.getElementById('box');
box.addEventListener('click',throttle(sayhi,2000));
注意
JavaScript 在事件处理函数中会提供事件对象 event,如果不加arguments
function throttle(fn,time){
let flag = true;
return function(){
if(!flag) return;
flag = false;
setTimeout(() => {
fn.apply(this);
console.log(this);
// console.log(arguments);
flag = true;
}, time);
}
}
function sayhi(e){
console.log("hello li");
console.log(e); // undefined
}
let box = document.getElementById('box');
box.addEventListener('click',throttle(sayhi,2000));
加上arguments后
function throttle(fn,time){
let flag = true;
return function(){
if(!flag) return;
flag = false;
setTimeout(() => {
fn.apply(this,arguments);
console.log(this);
flag = true;
}, time);
}
}
function sayhi(e){
console.log("hello li");
console.log(e); //
}
let box = document.getElementById('box');
box.addEventListener('click',throttle(sayhi,2000));

应用场景:
debounce
频繁操作点赞和取消点赞,因此需要获取最后一次操作结果并发送给服务器
throttle
鼠标不断点击触发,mousedown(单位时间内只触发一次)
window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用节流来让其只触发一次
网友评论