当前位置:网站首页>简单的写一个防抖跟节流
简单的写一个防抖跟节流
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>
边栏推荐
- Borg Maze (bfs+最小生成树)
- C#WPF 图片在显示时没有问题,但在运行时图片显示不出来的解决
- 22!Beijing Changping District notified catering service enterprises with food safety problems
- 矩阵键盘&基于51(UcosII)计算器小项目
- Loudi Sewage Treatment Plant Laboratory Construction Management
- 代码随想录笔记_动态规划_70爬楼梯
- 日志@Slf4j介绍使用及配置等级
- Ethernet channel Ethernet channel
- Wirshark common operations and tcp three-way handshake process example analysis
- Have you guys encountered this problem?MySQL 2.2 and 2.3-SNAPSHOT are like this, it seems to be
猜你喜欢
Wirshark common operations and tcp three-way handshake process example analysis
LeetCode medium topic search of two-dimensional matrix
bgp dual plane experiment routing strategy to control traffic
M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation
广东10个项目入选工信部2021年物联网示范项目名单
kubernetes介绍
金山云要飘到哪里?
[Study Notes] Persistence of Redis
【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
开源SPL消灭数以万计的数据库中间表
随机推荐
SecureCRTPortable – 破解
3DS MAX 批量导出文件脚本 MAXScript 带界面
C# WPF image is displayed without problems, but the solution does not display the image at runtime
OTA自动化测试解决方案---整体方案介绍
X5WebView使用
学习日记8
Redis上云迁移实践
Matlab画分段函数「建议收藏」
Basic knowledge of switches
Inventory of Loudi Agricultural Products Inspection Laboratory Construction Guidelines
【百度统计】用户行为分析
Drive IT Modernization with Low Code
鸿蒙开发从hello world开始
Fragment的show和hide
没有接班人,格力只剩“明珠精选”
G1和CMS的三色标记法及漏标问题
2022年五大云虚拟化趋势
Ethernet channel Ethernet channel
金山云要飘到哪里?
【iOS】面试整理