当前位置:网站首页>简单的写一个防抖跟节流
简单的写一个防抖跟节流
2022-08-10 13:07:00 【快乐的蜜蜂】
<!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>
边栏推荐
猜你喜欢
Ethernet channel 以太信道
Jenkins修改端口号, jenkins容器修改默认端口号
神了!阿里数据库专家纯手写了这份604页的Oracle+MySQL攻坚指南
商汤自研机械臂,首款产品是AI下棋机器人:还请郭晶晶作代言
Real-time data warehouse practice of Baidu user product flow and batch integration
How to describe multiple paragraphs with different font settings in Open Office XML format
Interface Automation Testing Basics
接口自动化测试基础篇
开源SPL消灭数以万计的数据库中间表
【ECCV 2022|百万奖金】PSG大赛:追求“最全面”的场景理解
随机推荐
Solution for "Certificate not valid for requested usage" after Digicert EV certificate signing
11 + chrome advanced debugging skills, learn to direct efficiency increases by 666%
Proprietary cloud ABC Stack, the real strength!
3DS MAX batch export file script MAXScript with interface
领域驱动实践总结(基本理论总结与分析V+架构分析与代码设计+具体应用设计分析)
Codeforces Round #276 (Div. 1) B. Maximum Value
Wirshark common operations and tcp three-way handshake process example analysis
jenkins数据迁移和备份
Overview of Loudi Petrochemical Experiment Design and Construction Planning
Fragment-hide and show
BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection Paper Notes
YTU 2295: KMP pattern match one (string)
学习日记8
神经网络可视化有3D版本了,美到沦陷!(已开源)
【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
想通这点,治好 AI 打工人的精神内耗
C# WPF image is displayed without problems, but the solution does not display the image at runtime
数字藏品,“赌”字当头
MYSQL误删数据恢复
在web页面播放rtsp流视频(webrtc)