First, to achieve a throttling function
@ Idea: triggered only once within a predetermined time
function Throttle ( Fn, Delay) {
// closure hold time using
the let PREV = Date.now ()
return function ( ) {
the let context = the this
the let Arg = arguments
the let now = Date.now ()
IF (now - PREV> = Delay) {
fn.apply (context, Arg)
PREV = Date.now ()
}
}
}
function Fn ( ) {
the console.log ( 'throttle')
}
the addEventListener ( 'Scroll', Throttle (Fn, 1000))
Second, implement an anti-shake function
@ Ideas: within a predetermined time is not triggered a second time, perform the
function Debounce ( Fn, Delay) {
// save timer closure using
the let Timer = null
return function ( ) {
the let context = the this
the let Arg = arguments
/ / triggered again within a predetermined period of time to clear the timer will reset the timer before
the clearTimeout (timer)
timer = the setTimeout ( function ( ) {
fn.apply (context, Arg)
}, Delay)
}
}
function Fn ( ) {
the console.log ( 'shake')
}
the addEventListener ( 'Scroll', Debounce (Fn, 1000))