<!--
* @Description:
* @Version: 1.0
* @Autor: Helx
* @Date: 2021-05-16 22:52:23
* @LastEditors: Helx
* @LastEditTime: 2021-11-18 19:19:13
-->
<!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>input防抖btn节流</title>
</head>
<body>
<div style="display:flex">
检索(防抖):<input id="inpt" type="type" />
点击(节流):<button id="btn">点我</button>
</div>
</body>
<script>
/* 为什么防抖和节流?
我们使用窗口的 resize,scorll,mousemove,mousehover;输入框等校验时,如果事件处理函数调用无限制,会加剧浏览器的负担,
尤其是执行了操作 DOM 的函数,那不仅造成计算资源的浪费,还会降低程序运行速度,甚至造成浏览的奔溃,影响用户体验。*/
//防抖:一段时间没触发事件,处理函数才执行,当再次触发事件,就重新开始计时
const debounce = function (fun, wait) {
let timer = null;
return function (args, t) {
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
fun(args, t);
}, wait);
}
}
//处理函数
const changeInput = (args, t) => {
console.log('args:', args, 't:', t);
}
const t1 = 1000;
const _debounce = debounce(changeInput, t1);
document.getElementById('inpt').oninput = function (e) {
const val = e.target.value;
_debounce(val, '输入框')
}
// 节流:当时间持续发生时,保证在一定时间段内只会处理一次事件函数
const throttle = function (fun, wait) {
let flag = false;
return function (arg, t) {
if (flag) return;
flag = true
setTimeout(function () {
fun(arg, t);
flag = false;
}, wait)
}
}
//处理函数
const onClick = args => {
console.log('args', args);
}
const t2 = 3000;
const _throttle = throttle(onClick, t2); //三秒钟内只能触发一次
document.getElementById('btn').onclick = function () {
console.log('11111');// 多次打印
_throttle('按钮触发');
}
</script>
</html>
函数-防抖和节流
最新推荐文章于 2024-08-06 17:16:47 发布