节流就像英雄的技能CD
举个例子:
剑圣的R技能冷却CD中不能发技能,冷却CD结束后,想在哪个时间点放技能都可以
节流的思想也是如此 开始的时候会执行fun函数一次,第二次执行fun函数与第一次fun函数执行的时间间隔必须不小于delay
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="#" rel="shortcut icon"/>
<title>Title</title>
</head>
<body>
<form action="" class="example-form">
<div>
<label for="name">
名称
</label>
<input autocomplete="off" class="input-ele" id="name" name="name" placeholder="please input your name"
type="text">
</div>
<div>
<label for="res">
输入
</label>
<textarea class="input-ele" id="res" name="res" placeholder="这里是每一次输入的结果" readonly
style="width: 500px;height: 500px" type="multipart"></textarea>
</div>
</form>
</body>
<script>
window.onload = function () {
const resEle = document.querySelector("#res");
function changeOutputVal(value) {
resEle.value += `\n${value}`;
}
/*
节流就像英雄的技能CD
举个例子:
剑圣的R技能冷却CD中不能发技能,冷却CD结束后,想在哪个时间点放技能都可以
节流的思想也是如此 开始的时候会执行fun一次,第二次执行fun与第一次fun执行的时间间隔必须不小于delay
*/
function throttle(fun, delay) {
//last:上一次执行fun函数的时间戳
let last, deferTimer
return function (args) {
//now获取当前时间戳
let now = +new Date();
if (last && now - last < delay) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = +new Date();
fun.call(this, args);
}, last - now + delay)
/*
为什么是last-now+delay而不是delay?
如果为delay时,当你点击触发throttle函数时,必须要等待delay才会执行,然而你点击触发throttle函数的那个时间点和上一次执行fun函数的时间点应该就忽略了,而节流是第二次执行fun与第一次执行fun的时间间隔必须不小于delay,不是你点击触发throttle函数的那个时间点和下一次执行fun的时间间隔不小于delay,
所以应该是last-now+delay而不是delay
*/
} else {
last = now;
fun.call(this, args);
}
}
}
const outputRes = throttle(changeOutputVal, 2000);
const inputEle = document.querySelector("#name");
inputEle.addEventListener("input", (eve) => {
outputRes(eve.target.value);
});
}
</script>
</html>