function throttle3(func, wait) {
var args, context;
var previous = 0;
var timeout;
var latter = function () {
previous = +new Date()
timeout = null
func.apply(context, args)
}
var throttled = function () {
var now = +new Date()
// 下次触发 func 剩余的时间
var remaining = wait - (now - previous)
context = this
args = arguments
// 如果更改了系统时间,或者没有剩余时间了
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now;
func.apply(context, args)
} else if (!timeout) {
timeout = setTimeout(latter, wait)
}
}
throttled.cancel = function () {
clearTimeout(timeout);
previous = 0;
timeout = null;
}
return throttled
}
【JavaScript】手写节流
于 2022-01-18 23:04:57 首次发布