JavaScript throttling and debounce

foreword

This article mainly records JavaScript throttling and anti-shake, throttling and anti-shake are essentially a means of optimizing the execution of high-frequency code.

For example: when the browser's mousemove, resize, scrolland other events are triggered, the bound event function will be called continuously, which greatly reduces the performance of the front end.

For performance optimization, it is necessary to limit the number of calls to such events. For this, we can use debounce and throttle to reduce the call frequency.

anti shake

After the high-frequency event is triggered, the function will only be executed once within n seconds. If the high-frequency event is triggered again within n seconds, the time will be recalculated .

Anti-shake principle

Maintain a timer , which stipulates that the function is triggered after the delay time , but if it is triggered again within the delay time , the current timer will be cleared and the timeout call will be reset, that is, the timer will be restarted .

Anti-shake disadvantages

If the event is continuously triggered within the specified time interval, the calling method will be continuously delayed;

sample code

	//防抖debounce代码:
	function debounce(fn) {
	    let timeout = null;
	    return function () {
	        clearTimeout(timeout); 
	        timeout = setTimeout(() => {
	            fn.apply(this, arguments);
	        }, 500);
	    };
	}
	// 处理函数
	function handle() {
	    console.log(Math.random());
	}
	// 给 window 添加滚动事件
	window.addEventListener('scroll', debounce(handle));

throttling

High-frequency event triggers, but only executes once in n seconds, throttling will dilute the execution frequency of the function ;

Throttling principle

The function is triggered by judging whether a certain time is reached. If the specified time is not reached, the timer is used to delay, and the next event will reset the timer.

The principle is to judge whether there is a delayed call function that has not been executed.

sample code

        //函数节流锁
        function throttle(fn, delay) {
            let Lock = true; 
            return function () {
                if (!lock) return;
                lock = false;
                setTimeout(() => { 
                    fn.apply(this, arguments);
                    lock = true;
                }, delay);
            };
        }

Comparative summary

The picture comes from the network infringement must be deleted

  • Function anti-shake: combine multiple operations into one operation ;

  • Function throttling: so that the event function is only triggered once within a certain period of time ;

This is the end of this article

If you have any other ideas, welcome to communicate in the comment area!

Guess you like

Origin blog.csdn.net/m0_47901007/article/details/125194294