We often use resize and Movesemove events in development. These events will frequently execute event binding procedures in a short period of time. We know that frequent DOM manipulation will bring great performance consumption, and the page will trigger backflow and redraw. Sometimes the page will stagnate and crash in Internet Explorer. This is where the throttling function comes into play.

What is anti-shake?

Simply speaking, a function cannot be called consecutively in a short period of time. Only when the specified time interval has passed after the last function execution can the next function be called. Or you don’t execute the function immediately when you do it, you wait until you don’t do it.

The timer is used to delay the execution of the function during operation. If the function is still operating within this time, the original timer is cleared and a new timer is created

/ ** * @{Function} callBack callBack * @{Number} delay * return {Function} * / Function debounce(callBack,delay=200){ var timer=null; return function(){ var context=this; clearTimeout(timer); Timer =>{callBack. Apply (context,arguments)},delay)}} // Call window.onresize=debounce(myFunc,300)Copy the code

What is throttling

In fact, the starting point of the anti-shake function is to make a function not to execute too often, reduce some fast calls to throttle, reduce performance consumption. When you operate the resize and Mousemove events, the browser actually sets a time interval, we don’t know how much time, and they don’t provide parameters to set, so we need to make some changes based on them. The real throttling should be to extend the call time as long as is acceptable, that is, we control the execution frequency and let the function call less to reduce computation and improve performance. If the original execution is 16ms once, if we find that resize every 50ms is acceptable, then 50ms is definitely a better time interval.

/ ** * @{Function} callBack callBack * @{Number} delay time * @{Number} intervalTime time * return {Function} * / function thorttleFn(callBack,delay,intervalTime){ var timer=null; Var time=0; Return function(){var context=this; var curTime=new Date(); // The current execution time clearTimeout(timer); // Clear the last timer if(! time){ time=curTime; } // Whether the time between the current execution time and the last execution time is greater than or equal to the interval if(curtime-time >= intervalTime){time=curTime; Callback.apply (context,arguments)}else{timer=setTimeout(()=>{callback.apply (context,arguments)},delay)}}} // call Window. Onresize = thorttleFn (myFunc, 50300)Copy the code