Home Web Front-end JS Tutorial Detailed explanation of JavaScript throttling function Throttle

Detailed explanation of JavaScript throttling function Throttle

Mar 07, 2017 pm 02:35 PM

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 (www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles