JavaScript-防抖
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JavaScript-防抖,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1892字,纯文字阅读大概需要3分钟。
内容图文
1. 功能
减少高频率执行代码的执行频率。
2.使用场景
- oninput
- onresize
- onscroll
- onmousemove
- onmousehover
- 等等
3.防抖原理
3.1 利用 setTimeout 延迟执行逻辑代码。
let timer = null;
element2.onkeyup = (event) => {
if (timer) {
window.clearTimeout(timer);
}
timer = setTimeout(() => {
console.log("防抖版本--发送网络请求:", event.target.value);
}, 1000);
};
3.2 封装工具函数
function debounce(fun, delay = 500) {
let timer = null;
return function () {
if (timer) {
window.clearTimeout(timer);
}
timer = setTimeout(() => {
//无法传递event参数
// fun();
fun.apply(this, arguments);
}, 1000);
};
}
4.示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>debounce防抖</title>
</head>
<body>
<div>
<span>原始版本:</span>
<input type="text" id="input" />
</div>
<div>
<span>防抖版本:</span>
<input type="text" id="debounce" />
</div>
<div>
<span>封装版本:</span>
<input type="text" id="function" />
</div>
<script>
//原始版本
const element = document.getElementById("input");
element.onkeyup = (event) => {
console.log("原始版本--发送网络请求:", event.target.value);
};
//防抖版本
const element2 = document.getElementById("debounce");
let timer = null;
element2.onkeyup = (event) => {
if (timer) {
window.clearTimeout(timer);
}
timer = setTimeout(() => {
console.log("防抖版本--发送网络请求:", event.target.value);
}, 1000);
};
//封装版本
const element3 = document.getElementById("function");
element3.onkeyup = debounce((event) => {
console.log("封装版本--发送网络请求:", event.target.value);
}, 1000);
function debounce(fun, delay = 500) {
let timer = null;
return function () {
if (timer) {
window.clearTimeout(timer);
}
timer = setTimeout(() => {
//无法传递event参数
// fun();
fun.apply(this, arguments);
}, 1000);
};
}
</script>
</body>
</html>
<!--输出结果-->
原始版本--发送网络请求: w
原始版本--发送网络请求: wo
原始版本--发送网络请求: wo'de
原始版本--发送网络请求: wo'de
原始版本--发送网络请求: 我的
防抖版本--发送网络请求: 我的
封装版本--发送网络请求: 我的
内容总结
以上是互联网集市为您收集整理的JavaScript-防抖全部内容,希望文章能够帮你解决JavaScript-防抖所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。