<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
防抖: <input />
节流: <div class="box"></div>
</body>
<script src="./classMyPromise.js"></script>
<script>
// 这个是 **防抖**的写法
const telInput = document.querySelector("input");
// 防抖是一段时间内,只允许一个进程, 如果有新进程来了, 把前面的进程给终止掉, 重新开始, 时间也重新开始计算
function debounce(fn, time) {
let timeout = null;
// 这个是要 通过一个 闭包来返回
return (...args) => {
// 这里 一定要清空定时器
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, args);
}, time);
}
}
telInput.addEventListener("input", debounce(demo, 2000));
function demo() {
console.log("我进来了");
}
// 这个是 **节流**的部分
function throttle(fn, time) {
let timer = null;
return (...args) => {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
// 如果时间到了 就把里面的定时器 给清空
timer = null;
}, time);
}
}
}
function demo2() {
console.log("我进来了...");
}
const boxEl = document.querySelector(".box");
boxEl.addEventListener("touchmove", throttle(demo2, 1000));
</script>
</html>
12-26
363