为什么要用到防抖和节流
前端代码的执行是基于浏览器的,频繁的进行某些计算或处理会占用更多的内存和CPU时间,可能会导致浏览器挂起,甚至是崩溃。
防抖和节流即是为了限制JS频繁的执行一段代码
防抖节流的定义及区别
防抖
连续的多次触发,固定的时间间隔内,存在新的触发,就清除之前的重新记时,满足时间执行一次——最新一次触发
节流
连续的多次触发,每一段固定的时间间隔内,我们只去执行一次——固定频率触发
图说
常见的应用场景
频繁操作dom,发送请求
视图窗口变化
window的 resize
键盘事件
文字输入时的 keyup 事件
鼠标事件
元素拖拽、移动时的 mousemove 事件;
按钮的不断点击;
滚轮滚动scroll 事件
各自的函数实现
防抖函数
/**
*fn:真正需要执行的函数
*delay:延时时间
*/
function debounce(fn, delay) {
var timer = null;
//这里使用闭包,方便我们自定义一些内部数据
return (...args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
//使用apply确保方法在适当的环境中执行
fn.apply(this,args);
}, delay);
}
}
节流函数
/**
*fn:真正需要执行的函数
*delay:延时时间
*/
function throttle(fn, delay){
var last = null,
return function () {
const now = + Date.now()
if(now > last + delay){
last = now
fn.apply(this,args)
}
}
}
实例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函数防抖节流</title>
</head>
<style>
.mytest{
width: inherit;
height: 200px;
background-color: antiquewhite;
align-items: center;
font-size: 50px;
display: flex;
justify-content: center;
}
</style>
<body>
<div class="mytest" >0</div>
</body>
<script>
function debounce(fn, delay) {
var timer = null;
return function () {
if (timer) clearTimeout(timer);
var _this = this;
var _arguments = arguments;
timer = setTimeout(function () {
fn.apply(_this,_arguments);
}, delay);
}
}
function throttle(fn, delay){
var timer = null,
booleanVal = false;
return function () {
if (booleanVal) {
return
}
booleanVal = true;
var _this = this;
var _arguments = arguments;
timer = setTimeout(function() {
fn.apply(_this,_arguments);
booleanVal = false;
},delay)
}
}
var div = document.querySelector('.mytest');
function foo() {
div.innerHTML = ++foo.count;
}
foo.count = 0;
div.onmousemove = throttle(foo,500);
</script>
</html>