节流函数:不管事件的触发频率有多高,只会间隔设定的时间执行一次目标函数。
有些场合只需要开始执行一次,后面的没必要了,为了保证性能与体验,采用节流 代码:
// 产出需要节流的方法 function throttle (func, delay = 500) { let isFlag = false return function(...args) { if (isFlag) return func.apply(this, args) isFlag = true setTimeout(() => { isFlag = false }, delay) } } // 要执行的方法 function throttleTest (args) { console.log(args) } (function () { // 返回需要节流的方法 let func = throttle(throttleTest, 1000) console.log(func) for (let i = 0; i< 10; i++) { // 执行方法并传参 func(123) } })()