防抖(debounce)
在事件被触发n秒后再执行回调函数,如果在这n秒内又被触发,则重新计时。简而言之就是连续的事件,只需触发一次即可。
使用场景有:
const _.debounce = (func, wait) => { let timer; return () => { clearTimeout(timer); timer = setTimeout(func, wait); } }
VUE.JS 中 使用:
new Vue({
el: "#app",
data: {
timeout2: null,
},
created(){},
methods: {
submit() {
// clearTimeout(this.timeout2) //方法一
// this.timeout2 = setTimeout(function(){console.log(‘点击‘)},600) //方法一
this.debounce2(function(){console.log(‘点击‘)},600,"timeout2") //方法二 抽离
},
debounce2(func, wait, obj) {
clearTimeout(this[obj])
this[obj] = setTimeout(func, wait) //返回计时器 ID
}
}
});
节流(throttle)
指限制一个函数在一定时间内只能执行一次。
使用场景:
原文:https://www.cnblogs.com/yangchin9/p/10397031.html