1 anti-shake + definition: Merge events and will not trigger the event, when the event is not triggered in a certain time, only really to trigger the event + principle: delay operation of the processing function, if the set delay before the arrival of the event again, it is clear that the last time delay operation timer, re-timer + Scenario: Verify user name on KeyDown event, input Method's Lenovo + implementation:
function debounce (FN, delay) { var timer; return function () { varthis; var args = arguments; Cleartimeout (timer); = SetTimeout (function() { fn.apply (that, args) ,}, delay);} }
2 throttle + definition: When an event is continuously triggered, the event is merged for a certain period of time, and then the event is actually triggered after an interval of certain events. Each interval of an event triggers a + scene: Resize changes the layout when onscroll scroll to add the following picture when loading. + implementation: 1. Using the timestamp > + principle: When triggering an event, we take out the current timestamp, then subtract the previous timestamp (the first value is set to 0), execute the function if it is greater than the set time period, and then update the timestamp to the current timestamp, and if it is less, do not. > + defect: The first event will be executed immediately, and the event cannot be activated after the stop is triggered.
function throttle (FN, interval) { Span style= "COLOR: #0000ff" >var previoustime = +new Date () return function Span style= "COLOR: #000000" > () { var that = this var args = arguments Span style= "COLOR: #0000ff" >var now = +new Date () if (now-previoustime >= Interva L) {previoustime = now fn.apply (that, args)}}}
1. Using the timer >+ principle: When the event is triggered, we set a timer, and then trigger the event, if the timer exists, do not execute until the timer executes, and then execute the function, emptying the timer, so that the next timer can be set. >+ defect: The first event will be executed after n seconds, and the event will still be executed once the trigger is stopped.
function Throttle (FN, interval) { var previoustime = +new Date () return function () { varThis var args = arguments var now = +new Date () if (now-previoustime >= interval) { = now fn.apply (that, args) }}}
1. Optimization > + mouse move can be executed immediately, stop the trigger can be executed again
function Throttle (FN, interval) { var previoustime = +new Date () return function () { varThis var args = arguments var now = +new Date () if (now-previoustime >= interval) { = now fn.apply (that, args) }}}
The original address: throttling and anti-shake implementation
Implementation of throttling and anti-shake