2

节流与防抖

 1 year ago
source link: https://www.fly63.com/article/detial/12191
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-09-29阅读: 9标签: 节流分享

扫一扫分享

概念:在规定的间隔时间范围内不会重复触发回调,只有大于这个时间间隔才会触发回调,把频繁触发变为少量触发。

类似于技能CD。

应用:点击按钮,轮播图点击左右箭头。

插件lodash.js,它里面封装了函数的防抖与节流业务。

<p>计数器:<span>0</span></p> <button>+1</button> // 获取元素 let span = document.querySelector('span') let btn = document.querySelector('button') let count = 0 let timer = null // 控制节流阀是否开启或关闭 let flag = true // 需求:在一秒以内,不管点击按钮多少次,计数器数值只能+1 btn.onclick = function () { if (flag) { flag = false timer = setTimeout(() => { count++ span.innerhtml = count flag = true }, 1000) } }

概念:前面的所有的触发都被取消,最后一次执行在规定的时间之后才会触发,也就是说如果连续快速的触发,只会执行一次。

类似于LOL回城被打断。

应用:输入框搜索。

插件lodash.js,它里面封装了函数的防抖与节流业务。

<input type="text" @input="inputFn" /> data () { return { timer: null } }, methods: { inputFn () { if (this.timer) { clearTimeout(this.timer) } this.timer = setTimeout(() => { // 发送网络请求 }, 3000) } }

链接: https://www.fly63.com/article/detial/12191


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK