节流防抖封装
防抖:在持续触发事件时,一定时间内没有再次触发,函数才会执行,若时间内再次触发,将继续延时
节流:在持续触发事件时,一定时间内只执行一次函数
/** * 防抖 * @param {function} func 函数 * @param {int} time 毫秒 */ let timeout = null; function AntiShake(func,time){ return function(){ // 判断定时器是否已存在,若存在则清除重新定时 if(timeout != null){ clearTimeout(timeout) timeout = null } timeout = setTimeout(func, time); } } /** * 节流 * @param {function} func 函数 * @param {int} time 毫秒 */ let starttime = Date.now() function throttleOne(func,time){ return function() { let endtime = Date.now() if (endtime - starttime > time) { func() starttime = Date.now() } } } let status = true function throttleTwo(func,time){ return function() { if(!status){ return } status = false setTimeout(() => { func() status = true }, time); } } export { AntiShake, throttleOne, throttleTwo }