Home >Web Front-end >JS Tutorial >JavaScript Topic 4: Throttling

JavaScript Topic 4: Throttling

coldplay.xixi
coldplay.xixiforward
2021-03-05 09:41:012445browse

JavaScript Topic 4: Throttling

Contents

  • Preface
  • 1. Core and basic implementation
  • 2. Throttling Advanced
  • Write at the end

(Free learning recommendation: javascript video tutorial )

Preface

Let’s talk about throttling - the idea of ​​another optimization function.

Let’s take the mobile event as an example

nbsp;html>
    <meta>
    <meta>
    <meta>
    <title>Document</title>
    <style>
        #wrapper {
            width: 100%;
            height: 140px;

            background: rgba(0, 0, 0, 0.8);

            color: #fff;
            font-size: 30px;
            font-weight: bold;
            line-height: 140px;
            text-align: center;
        }
    </style>
    <p></p>

    <script>
        var count = 1;
        function moveAction () {
            oWrapper.innerHTML = count++;
        }

        var oWrapper = document.querySelector(&#39;#wrapper&#39;);
		oWrapper.onmousemove = moveAction;
    </script>

The effect is as follows:

JavaScript Topic 4: Throttling

1. Core and basic implementation

The principle of throttling is very simple: If you continuously trigger an event, it will only be executed once within a specific time interval.

Regarding the implementation of throttling, there are two mainstream implementation methods:

  1. Time stamp idea
  2. Timer idea

1.1 Timestamp idea

As the name suggests, the time interval is controlled through two timestamps. When an event is triggered:

  1. We take out the current Timestamp now;
  2. Then subtract the timestamp of the previous execution (the first value is 0) prev;
  3. If bignow - prev > wait, it proves that the time interval maintenance is over, executes the specified event, and updates prev;

According to this idea, we You can now implement the first version of the code:

oWrapper.onmousemove = throttle(moveAction, 1000);function throttle(func, wait) {
    var _this, arg;
    var prev = 0; // 上一次触发的时间,第一次默认为0

    return function () {
        var now = Date.now(); // 触发时的时间
        _this = this;
        if (now - prev > wait) {
            func.apply(_this, arg); // 允许传入参数,并修正this
            prev = now; // 更新上一次触发的时间
        }
    }}

Let’s see what the effect is like with the help of it:

JavaScript Topic 4: Throttling

We can see:

  1. When the mouse moves in, the event is executed immediately
  2. It will be executed once every 1s, and it will be executed twice after moving for 2.5s, which means the action will not be executed again after stopping.

1.2 Timer idea

Use timer to ensure the number of triggers of events within the interval

  1. Create timertimer , record whether it is currently within the period;
  2. Determine whether the timer exists, if it exists, it will end directly, otherwise the event will be executed;
  3. wait time Then execute it again and clear the timer;

When the event is triggered, we set a timer. When the event is triggered again, if the timer exists, it will not be executed until the timer is executed. , and then execute the function to clear the timer, so that the next timer can be set.

function throttle(func, wait) {
    var _this, arg;
    var timer; // 初始化
    return function () {
        _this = this; // 记录this
        arg = arguments; // 记录参数数组
        if (timer) return; // 时候未到
        timer = setTimeout(() => {
            func.apply(_this, arg); // 允许传入参数,并修正this
            timer = null;
        }, wait);
    }}

Let’s see what the effect is like with the help of it:

JavaScript Topic 4: Throttling

However, we can see:

  1. When the mouse is moved in, the event will not be executed immediately;
  2. After the mouse is customizedwaitIt will be executed once after an interval

1.3 The difference between the two ideas

##TimestampTimer "Start point"Execute immediatelyExecute after n seconds"End point"Will not be executed after stoppingStop will be executed again

2. Throttling advancement

Combining two ideas to complete one can be executed immediately , and the throttling method to execute again after stopping the trigger:

// 第三版function throttle(func, wait) {
    var timeout, context, args, result;
    var previous = 0;

    var later = function() {
        previous = +new Date();
        timeout = null;
        func.apply(context, args)
    };

    var throttled = function() {
        var now = +new Date();
        //下次触发 func 剩余的时间
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
         // 如果没有剩余的时间了或者你改了系统时间
        if (remaining  wait) {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            func.apply(context, args);
        } else if (!timeout) {
            timeout = setTimeout(later, remaining);
        }
    };
    return throttled;}
The effect is demonstrated as follows:

JavaScript Topic 4: Throttling

When I was looking at the code, I printed it repeatedly Only with data can we understand why we do this, let’s work hard~

Related free learning recommendations: javascript (Video)

The above is the detailed content of JavaScript Topic 4: Throttling. For more information, please follow other related articles on the PHP Chinese website!

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