emmm…,在文章开始前,我想问大家一个问题,就是 当你对象在和你发消息时,把一句完整的话,拆分成一个字一个字发给你时,你当时的感受会是什么样的呢?
我想,大部分的当事人内心都应该是想:我TM的怕不是找了个傻子吧!
我们来模拟一下憨憨的对象发送信息时的场景:
<!-- html代码片段 -->
<!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>
<body>
<div class="wrapper">
<input type="text">
</div>
</body>
</html>
复制代码
// js代码片段
const input = document.querySelector('input');
input.oninput = function(e) {
console.log(this.value)
}
复制代码
效果动图:
假设我们正在玩着游戏,突然你的憨憨对象一直这样在对你进行消息轰炸,我想你应该会让他(她)见识一下什么叫做砂锅大的拳头吧~
那么我们换位思考一下,当我们和后端进行数据请求的时候,请求的数据一直处于一个高频率更新的状态,可能会导致页面的延迟或者是卡顿,特别影响用户的体验。所以我们今天请来了一位老大哥好好的解决这个问题(让你的对象好好聊天!)
老大哥的自我介绍:
姓名:防抖
英文名:debounce
真身:一个函数
特长:教会你的对象怎么好好聊天~ (当你触发事件后,如果在 n 秒内,没有再次触发该事件,那么就执行函数;如果在 n 秒内,再次触发了该事件,那么就取消计时器,重新开始计时)
我们先来看看老大哥的真身吧~
function debounce(fn, time) {
let timer = null; // 定时器的引用
return function () {
const _this = this; // 防止 this 指向错误,所以这边需要存一下 this 的值
const args = Array.from(arguments);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn.apply(_this, args)
}, time)
};
}
复制代码
当我们的对象经过老大哥的教训,终于会好好聊天啦~,具体看下面的代码片段和效果图:
<!-- html代码片段 -->
<!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>
<body>
<div class="wrapper">
<input type="text">
</div>
</body>
</html>
复制代码
// js代码片段
const input = document.querySelector('input');
function debounce(fn, time) {
let timer = null;
return function () {
const _this = this;
const args = Array.from(arguments);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn.apply(_this, args)
}, time)
};
}
input.oninput = debounce(
function (e) {
console.log(this.value)
},
1000
)
复制代码
效果动图:
嘻嘻,经过老大哥的帮助,我们那个憨憨的对象终于会好好聊天啦~
你们的对象还有什么小问题呀,评论区留言,下次帮你解决~
公众号: 前端小轩,欢迎来给你的对象挂号治疗呀~
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END