Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-09-28 15:45:26
forward
1950 people have browsed it

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);
            }
        };
    }
Copy after login

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);
        };
    }
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!