1 if you
1.1 define
If an event is triggered continuously and no event is triggered within a period of time, the event is executed once. If it is triggered again during this period of time, the timer will be restarted. It can be understood as the "forward shake" of the skills in the game.Copy the code
1.2 Application Scenarios
1. Continuous Input in the Input box. 2. 3. When changing the size of the browser window, you also need to use the stabilization because the resize times are too frequent.Copy the code
Before shaking: Triggers the onMousemove event
After shaking: Triggers the onMousemove event
1.3 Code implementation
Function debounce(fn, delay) {let timer = null; Args) => {// determine if the timer has a value, If (timer) clearTimeout(timer) timer = setTimeout(() => {fn.apply(this,args)},delay)}} Window.onresize = debounce (function() {console.log('dobounce', arguments)},500) window.onresize = debounce (function() {console.log('dobounce', arguments)},500)Copy the code
2 the throttle
1.1 define
Let high-frequency events fire, only once every n seconds; This can be interpreted as a "cooling down" of in-game skills.Copy the code
1.2 Application Scenarios
1. Scroll event, calculate the position every n seconds. 2. The mouseDown event is triggered every n seconds.Copy the code
Throttling:
1.3 Code implementation
Let pre = 0 return (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0). Args) => {let now = new Date().gettime () if(now-pre > delay) {fn.apply(this, args) pre = now}}} Window.onresize = throttle (function() {console.log(' arguments')},500) window.onresize = throttle (function() {console.log(' arguments')},500)Copy the code
Let timer = null return (... args) => { if(! Timer){timer = setTimeout(() => {fn.apply(this, args)}, delay)}}} Window.onresize = throttle (function() {console.log(' arguments')},500) window.onresize = throttle (function() {console.log(' arguments')},500)Copy the code