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

Detailed explanation of JavaScript throttling function Throttle

黄舟
Release: 2017-03-07 14:35:47
Original
1083 people have browsed it

In the browser DOM events, there are some events that will be triggered continuously along with the user's operations. For example: resize the browser window (resize), scroll the browser page (scroll), and move the mouse (mousemove). That is to say, when the user triggers these browser operations, if the corresponding event processing method is bound to the script, this method will be triggered continuously.

This is not what we want, because sometimes if the event processing method is relatively large, the DOM operation is complex, and such events are continuously triggered, it will cause performance losses and reduce the user experience ( UI response is slow, browser freezes, etc.). So generally speaking, we will add delayed execution logic to the corresponding event.

Usually we use the following code to implement this function:

var COUNT = 0;
function testFn() { console.log(COUNT++); }
// 浏览器resize的时候
// 1. 清除之前的计时器
// 2. 添加一个计时器让真正的函数testFn延后100毫秒触发
window.onresize = function () {
    var timer = null;
    clearTimeout(timer);

    timer = setTimeout(function() {
        testFn();
    }, 100);
};
Copy after login

Careful students will find that the above code is actually wrong. This is a problem that novices will make: setTimeout function The return value should be stored in a relative global variable, otherwise a new timer will be generated every time it is resized, which will not achieve the effect we sent

So we modified the code:

var timer = null;
window.onresize = function () {
    clearTimeout(timer);
    timer = setTimeout(function() {
        testFn();
    }, 100);
};
Copy after login

The code is now normal, but there is a new problem - a global variable timer is generated. This is what we don't want to see. If this page has other functions also called timer, different codes will conflict before. In order to solve this problem, we need to use a language feature of JavaScript: closure closure. Readers with relevant knowledge can go to MDN to learn about it. The modified code is as follows:

/**
 * 函数节流方法
 * @param Function fn 延时调用函数
 * @param Number delay 延迟多长时间
 * @return Function 延迟执行的方法
 */
var throttle = function (fn, delay) {
    var timer = null;

    return function () {
        clearTimeout(timer);
        timer = setTimeout(function() {
            fn();
        }, delay);
    }
};
window.onresize = throttle(testFn, 200, 1000);
Copy after login

We use a closure function (throttle throttling) to put the timer internally and return the delay processing function, so that the timer variable is exposed to the outside world. It is invisible, but the timer variable can also be accessed when the internal delay function is triggered.

Of course, this way of writing is difficult to understand for novices. We can change it to another way of writing to understand it:

var throttle = function (fn, delay) {
    var timer = null;

    return function () {
        clearTimeout(timer);
        timer = setTimeout(function() {
            fn();
        }, delay);
    }
};

var f = throttle(testFn, 200);
window.onresize = function () {
    f();
};
Copy after login

Here are the main points to understand: Throttle After being called The returned function is the real function that needs to be called when onresize is triggered

Now it seems that this method is close to perfect, but in actual use it is not the case. For example:

If the user continuously resizes the browser window size, then the delay processing function will not be executed even once

So we Another function needs to be added: when the user triggers resize, it should trigger at least once within a certain period of time . Since it is within a certain period of time, then this judgment condition can take the current time milliseconds, each time This function call subtracts the current time from the last call time, and then determines that if the difference is greater than a certain period of time, it will be triggered directly. Otherwise, the delay logic of timeout will still be used.

What needs to be pointed out in the following code is:

  1. The role of the previous variable is similar to that of timer. They both record the last identification and must be a relative global variable

  2. If the logic flow follows the logic of "trigger at least once", then the function call needs to be reset to the current time, which simply means: relative to the next time In fact, this is the current

/**
 * 函数节流方法
 * @param Function fn 延时调用函数
 * @param Number delay 延迟多长时间
 * @param Number atleast 至少多长时间触发一次
 * @return Function 延迟执行的方法
 */
var throttle = function (fn, delay, atleast) {
    var timer = null;
    var previous = null;

    return function () {
        var now = +new Date();

        if ( !previous ) previous = now;

        if ( now - previous > atleast ) {
            fn();
            // 重置上一次开始时间为本次结束时间
            previous = now;
        } else {
            clearTimeout(timer);
            timer = setTimeout(function() {
                fn();
            }, delay);
        }
    }
};
Copy after login

practice:

We simulate a throttling scenario when a window scrolls, that is to say, when the user scrolls down the page, we need to throttle the execution. Some methods, such as: calculating DOM position and other actions that require continuous manipulation of DOM elements

The complete code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>throttle</title>
</head>
<body>
    <p style="height:5000px">
        <p id="demo" style="position:fixed;"></p>
    </p>
    <script>
    var COUNT = 0, demo = document.getElementById(&#39;demo&#39;);
    function testFn() {demo.innerHTML += &#39;testFN 被调用了 &#39; + ++COUNT + &#39;次<br>&#39;;}

    var throttle = function (fn, delay, atleast) {
        var timer = null;
        var previous = null;

        return function () {
            var now = +new Date();

            if ( !previous ) previous = now;
            if ( atleast && now - previous > atleast ) {
                fn();
                // 重置上一次开始时间为本次结束时间
                previous = now;
                clearTimeout(timer);
            } else {
                clearTimeout(timer);
                timer = setTimeout(function() {
                    fn();
                    previous = null;
                }, delay);
            }
        }
    };
    window.onscroll = throttle(testFn, 200);
    // window.onscroll = throttle(testFn, 500, 1000);
    </script>
</body>
</html>
Copy after login

We use two cases to test the effect, which are to add at least trigger atleast parameters and Without adding:

// case 1
window.onscroll = throttle(testFn, 200);
// case 2
window.onscroll = throttle(testFn, 200, 500);
Copy after login

case 1 behaves as follows: testFN will not be called during the page scrolling process (cannot be stopped), and will be called once when it stops, that is to say, it will be executed The last in throttle is a setTimeout, the effect is as shown in the figure (view the original gif picture):

##case 2 behaves as : During the process of page scrolling (cannot be stopped), testFN will be executed with a delay of 500ms for the first time (from at least delay logic), and then executed at least every 500ms. The effect is as shown in the figure

So far, the effect we want to achieve has been basically completed. Readers can figure out some subsequent auxiliary optimizations by themselves, such as: function this points to, return value storage, etc.

Quote

  1. Test code http://jsbin.com/tanuxegija/edit

  2. Full version code http:/ /jsbin.com/jigozuvuko

  3. Debounce VS throttle https://github.com/dcorb/debounce-throttle

The above is the detailed explanation of the JavaScript throttling function Throttle. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

source:php.cn
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!