节流实现

1、节流实现

/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
*/
const throttle = (fn, wait) => {
    // 上一次执行 fn 的时间
    let previous = 0
        // 将 throttle 处理结果当作函数返回
    return function(...args) {
        // 获取当前时间,转换成时间戳,单位毫秒
        let now = +new Date()
            // 将当前时间和上一次执行函数的时间进行对比
            // 大于等待时间就把 previous 设置为当前时间并执行函数 fn
        if (now - previous > wait) {
            previous = now
            fn.apply(this, args)
        }
    }
}
//需要执行的函数
function printNum() {
console.log('执行了')
}
// 执行 throttle 函数返回新函数
const betterFn = throttle(printNum, 2000)
// 点击界面的box
var box = document.getElementById('box');
box.onclick = function() {
betterFn();
}
原文地址:https://www.cnblogs.com/qianqiang0703/p/14890668.html