Home  >  Article  >  Web Front-end  >  Implementation of function throttling and anti-shake in Javascript (with code)

Implementation of function throttling and anti-shake in Javascript (with code)

不言
不言forward
2018-09-28 15:43:572006browse

The content of this article is about the implementation of function throttling and anti-shake in Javascript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Function throttling (throttle)

Explanation of terms

Function throttling (throttle): Continuously execute functions and execute functions at regular intervals

Use Scenario

Mouse movement, mousemove event
DOM element dynamic positioning, window object resize and scroll events
etc...

Simple implementation of function throttling

    function throttle(fn, delay) {
        var last; // 上次执行的时间
        var timer; // 定时器
        delay || (delay = 250); // 默认间隔为250ms
        return function() {
            var context = this;
            var args = arguments;
            var now = +new Date(); // 现在的时间
            if (last && now < last + delay) { // 当前距离上次执行的时间小于设置的时间间隔
                clearTimeout(timer); // 清除定时器
                timer = setTimeout(function() { // delay时间后,执行函数
                    last = now;
                    fn.apply(context, args);
                }, delay);
            } else { // 当前距离上次执行的时间大于等于设置的时间,直接执行函数
                last = now;
                fn.apply(context, args);
            }
        };
    }

Function debounce (debounce)

Explanation of terms

Function debounce (debounce): The calling method will only be executed when the idle time must be greater than or equal to a certain value

Usage scenarios

Text input keydown event
Wait...

Simple implementation of function anti-shake (debounce)

    function debounce(fn, delay) {
        var timer; // 定时器
        delay || (delay = 250); // 默认空闲时间250ms
        return function() {
            var context = this;
            var args = arguments;
            clearTimeout(timer); // 清除定时器
            timer = setTimeout(function() { // delay时间后,执行函数
                fn.apply(context, args);
            }, delay);
        };
    }

The above is the detailed content of Implementation of function throttling and anti-shake in Javascript (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more