Throttling: within the specified time, repeatedly triggering event, but performed only once
Scene: a search input box, map rendering
Optimize the user experience
/ * * * Throttle within a specified time no matter how many times the trigger is executed only once * {Function} @param fn actual business logic functions to be performed * @param {Number} duration specified period of time, the business logic function can only be performed once milliseconds * / function Throttle (Fn, DURATION) { the let PREV = Date.now (), timerId = null return function () { the let now = Date.now () the let args = arguments the clearTimeout (timerId) // must Clear timer in advance, because the branch else can execute, set a timer, if satisfied if the second trigger condition, the total will be executed twice if ((now - prev)> = DURATION) { // to a predetermined time , the function execution setting fn.apply ( the this , args) prev = now } the else { // no predetermined timing, but the event is triggered, re-starting a timer timerId the setTimeout = (() => { // here to ensure that at least once, or fail if conditions function will not perform a PREV = now fn.apply ( the this , args) }, DURATION) } } }
Image Stabilization: multiple trigger events to trigger the last time to start, delayed by a predetermined time to perform
Scene: Load picture browser when scrolling, click the submit button
Optimize performance
/ * * * Shake no matter how many times the trigger event to trigger the last time to prevail, the time delay setting execution * @param {Function} function fn actual business logic to be executed * @param {Number} duration in the period after the business logic function begins execution in milliseconds * / function Debounce (Fn, DURATION) { the let timerId = null return function () { the clearTimeout (timerId) // every trigger are required to clear the timer and re-starting a timer = the setTimeout timerId (() => { fn.call ( the this , arguments) }, DURATION) } }
Sometimes the throttle and image stabilization can be used interchangeably, look at business needs, not so rigid