闭包机制:将内层函数环境返回给外层函数,只要内层函数环境被使用外层函数环境就不会被销毁。
两者区别:函数防抖和函数节流都是防止某一时间频繁触发,但是它们的原理不一样;
函数防抖只会执行最后一次,而函数节流是在规定 的时间内执行;
节流:在规定的时间内执行一次,保留上一次的执行时间
function throttle (fn = () => { }, delay = 500) {
let startTime = new Date().getTime()
return function (...arg) {
let executeTime = new Date().getTime()
if (executeTime - startTime > delay) {
fn.apply(this, arg)
startTime = executeTime
}
}
}
防抖:一个函数如果触发多次,清除上一次的执行时间重新开始计时,只执行最后一次。
function debounce (fn = () => { }, delay = 500) {
let time = null
return function (...arg) {
const that = this
if (time) {
clearTimeout(time)
}
time = setTimeout(function () {
fn.apply(that, arg)
}, delay)
}
}