节流
节流是将多次执行变成每隔一段时间执行。
场景: 在监听页面滚动的时候滚轮滚动一下会连续执行n多次回调函数,这样造成性能的损耗, 使用节流能够非常好的节省性能的损耗。
eg:
未使用节流 window.onscroll = function(){ console.log("scrolling")};
//鼠标滚一下,连续触发了13次。。
使用节流函数 window.onscroll = throttle(function(){ console.log("scrolling")}, 100);
//鼠标滚一下,只触发了一次
节流函数的简单实现
function throttle(fn, delay){
if(typeof fn !== "function"){
return new Error("argument[0] is not a function")
}
let context = this;
let timer = null;
return function(...args){
if(!timer){
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, delay)
}
}
}
防抖
防抖是将连续触发改变为直到最后一次且等待时间超过设定时间在执行,期间都会重新计时;
场景: 在输入input输入联想的时候,不使用防抖则会不停的发送ajax请求,造成资源浪费。
防抖简单实现
function debounce(fn, delay) {
if(typeof fn !== "function"){
return new Error("argument[0] is not a function");
}
let context = this;
let now = Date.now();
let timer = null;
return function(...args){
let remain = Date.now() - now;
//如果连续操作时间小于delay的时间则清空定时器,继续重新设定
if(remain < delay){
clearTimeout(timer);
timer = null;
now = Date.now();
timer = setTimeout(() => {
fn.apply(context, args);
}, delay)
}
}
}
//完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>防抖</title>
</head>
<body>
<input type="text" id="ipt" />
<script>
function debounce(fn, delay) {
if (typeof fn !== "function") {
return new Error("argument[0] is not a function");
}
let context = this;
let now = Date.now();
let timer = null;
return function (...args) {
let remain = Date.now() - now;
//如果连续操作时间小于delay的时间则清空定时器,继续重新设定
if (remain < delay) {
clearTimeout(timer);
timer = null;
now = Date.now();
timer = setTimeout(() => {
fn.apply(context, args);
}, delay)
}
}
}
document.getElementById("ipt").addEventListener("input", debounce((e) => {
console.log(e.target.value)
}, 1000))
</script>
</body>
</html>