/** * 节流函数 * 第一次会触发,最后一次会触发 */ functiontrottle (func, wait) { let context, args, timeout let old = 0// 时间戳 let later = function () { old = newDate().valueOf() timeout = null func.apply(context, args) } returnfunction () { context = this args = arguments let now = newDate().valueOf() if (now - old > wait) { if (timeout) { clearTimeout(timeout) timeout = null } func.apply(context, args) old = now }
if (!timeout) { timeout = setTimeout(later, wait) } } }
/** * 节流函数 * 最终版本 * 第一次不会触发,最后一次会调用 leading:false, trailing:true * 第一次会触发,最后一次不会触发 leading:true, trailing:false */ functiontrottle (func, wait, options) { let context, args, timeout, result let old = 0// 时间戳 if (!options) options = {} let later = function () { old = newDate().valueOf() timeout = null result = func.apply(context, args) } let trottled = function () { context = this args = arguments let now = newDate().valueOf() if (options.leading === false && !old) { old = now; } if (now - old > wait) { if (timeout) { clearTimeout(timeout) timeout = null } result = func.apply(context, args) old = now }
if (!timeout && options.trailing !== false) { timeout = setTimeout(later, wait) } return result } trottled.cancel = function () { clearTimeout(timeout) timeout = null } return trottled }