时间戳实现
当触发时间相加大于500毫秒时执行 触发和执行同时 无法保证最后一次触发一定执行
function throttle ( callback, duration = 500 ) {
let prevTime = Date. now ( )
return function ( ) {
let now = Date. now ( )
if ( now - prevTime > duration) {
callback ( )
prevTime = now
}
}
}
let initTime = Date. now ( )
setInterval ( throttle ( function ( ) {
console. log ( Date. now ( ) - initTime)
} ) , 300 )
定时器实现
执行在触发后500毫秒 300时触发800时执行,之后最近一次触发是900,触发后1400执行 无法保证最后一次触发一定执行
function throttle ( callback, duration = 500 ) {
let timer = null
return function ( ) {
if ( ! timer) {
timer = setTimeout ( function ( ) {
callback ( )
timer = null
} , duration)
}
}
}
let initTime = Date. now ( )
setInterval ( throttle ( function ( ) {
console. log ( Date. now ( ) - initTime)
} ) , 300 )
综合实现
最后一次触发一定执行 执行稳定,执行随触发时间和延时中最大的值
function throttle ( callback, duration = 500 ) {
let timer = null ;
let prevTime = Date. now ( )
return function ( ) {
if ( timer) clearInterval ( timer)
let curTime = Date. now ( )
let time = duration - ( curTime - prevTime)
if ( time <= 0 ) {
callback. apply ( this , arguments)
prevTime = Date. now ( )
} else {
timer = setTimeout ( ( ) => {
callback. apply ( this , arguments)
prevTime = Date. now ( )
} , time)
}
}
}
let initTime = Date. now ( )
setInterval ( throttle ( function ( ) {
console. log ( Date. now ( ) - initTime)
} ) , 300 )