节流的实现方式

时间戳方式

function throttle(func, delay) {
        // 首先获取使用节流机制时的时间
var prev = Date.now(); return function () {
          // 再获取调用时的时间
var now = Date.now(); var context = this; var args = arguments;
          // 若两个时间差超过了设置的时间,调用函数
if (now - prev >= delay) { func.apply(context, arguments) } prev = Date.now; } }

定时器方式

设置定时器,延迟时间后执行相应函数,并清除该定时器。后续函数调用,必须在定时器为null的情况下,才能执行。

function throttle(func, delay) {
            var timer = null;
            return function () {
                var context = this;
                var args = arguments;
                if (!timer) {
                    timer = setTimeout(()=>{
                        func.apply(context, args)
                        clearTimeout(timer)
                    },delay)
                }
            }
        }
原文地址:https://www.cnblogs.com/ashen1999/p/12924866.html