// 节流,控制函数的执行频率,一定时间间隔内只执行一次
function throttle (func, delay) {
if (typeof func !== 'function') {
return
}
let lastTime = 0
return function() {
const currentTime = new Date().getTime()
if (currentTime - lastTime >= delay) {
func.apply(this, arguments)
lastTime = currentTime
}
}
}
function fun(params) {
console.log('节流', params)
}
const throttleFun = throttle(fun, 1000)
// 一秒钟多次被调用,但是只会执行一次
throttleFun(1)
setTimeout(() => {
throttleFun(2)
}, 200);
setTimeout(() => {
throttleFun(3)
}, 1000);