throttle

278 阅读1分钟
/*
 * @Author: beth.miao 
 * @Date: 2018-08-03 17:16:31 
 * @Last Modified by: beth.miao
 * @Last Modified time: 2018-08-03 18:04:06
 */

// 简版
//  interval等待时间间隔
function throttle(fn, interval = 300){
    var canRun = true;  // 设置开关
    return function () {  // 返回闭包函数 canRun保留作用域
        if (!canRun) return; // 判断开关  
        canRun = false; // 立刻关闭开关
        setTimeout(() => {  // interval时间之后执行cb并恢复开关
            fn.apply(this, arguments);
            canRun = true;
        }, interval);
    };
}
function logTime(){
    console.log(new Date().getTime());
}
// 控制台测试
document.addEventListener('scroll',throttle(logTime, 1000))