您的位置:首页 > Web前端

前端节流和防抖(下)

2020-04-10 19:11 615 查看

节流和防抖(下)

节流

在(限定时间段内)只触发一次函数,
比如 规定时间间隔为1s ,那这个函数在1s内只执行1次
不管用户触发多少次事件,我触发函数后,1s后才能重新触发
<input class="inp" type="text" />
let input = document.querySelector('.inp');

//间隔1s时间,输出用户在input框的输入
function showVal(e) {
// console.log('this==>', this)
console.log('this.value', this.value);
console.log('e==>', e.target);
}

// 节流函数
function throttle(fn, delay) {
// 被内层函数保护的变量
let bool = false;
return function () {
// 拦截层,当函数正在运行时不执行
if (bool) {
return;
}

// 挂牌函数正在运行
bool = true;

setTimeout(() => {
// 执行函数
fn.apply(this, arguments); //this和arguments分别是修正this指向和修正参数列表

// 函数执行完毕,把牌子去掉
bool = false;
}, delay)
}
}
//绑定监听用户输入事件
input.oninput = throttle(showVal, 1000);
  • 点赞
  • 收藏
  • 分享
  • 文章举报
chenjinyu_lxl 发布了11 篇原创文章 · 获赞 0 · 访问量 109 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: