This is the 18th day of my participation in Gwen Challenge

foreplay

First, to summarize the content of the previous article, simple Code implementation of “shock prevention” for front-end JavaScript: “Shock prevention” is the delayed execution of some processing logic after a high-frequency trigger event has stopped firing.

While anti-shaking optimizes performance to a certain extent, it has its limitations: if high frequency events keep firing, the logic in the callback function never executes.

As you all know, the Nuggets editor has a draft box effect, meaning that what you type is saved, even if you exit the editor page, you can still retrieve it when you enter it again. This is because the editor’s input event performs a shaker-proof function for sending content. As shown below:

Now let’s say you type so fast that you almost never take a breather. Will that result in you not saving data for a long time? If you shut down the browser as fast as you can, won’t your content be saved?

So can we find a way to avoid the above situation?

In this context, our hero today – “throttle” began to come on stage.

Throttling means executing the logic in the callback function at regular intervals.

Instead of using the throttling function, let’s look at the following function in action:

<body>
    <form action="" class="example-form">
        <div>
            <label for="name">The name of the</label>
            <input class="input-ele" type="text" name="name" id="name" placeholder="please input your name"
                autocomplete="off">
        </div>
        <div>
            <label for="res">The input</label>
            <textarea class="input-ele" type="multipart" name="res" id="res" readonly
                placeholder="Here is the result of each input."></textarea>
        </div>
    </form>
</body>

<script>
    window.onload = () = > {
        const inputEle = document.querySelector("#name");
        const resEle = document.querySelector("#res");
        inputEle.addEventListener("input".function (event) {
            console.log(this.value);
            resEle.value += `\nThe ${this.value }`
        });
    }
</script>
Copy the code

The results are as follows:

Even if we want to execute the output logic, we can’t accept the output with such a high frequency. One is that the output content is redundant, and the other is that the rendering intensity is high, which is not cost-effective.

The new demand

Suppose we have a new requirement to add logic to the input event: the logic in the callback function will be executed once in a while.

This requirement is suitable for the throttling function usage scenario, so let’s implement one.

The savings

According to the definition of the throttling function, the code logic is executed at a fixed low frequency. Specifically, for our requirements above, whenever the page is opened, the logic to save data is executed every few seconds, regardless of whether you have input.

window.onload = function () {
    const resEle = document.querySelector("#res");
    function changeOutputVal(value) {
        resEle.value += `\n${ value }`;
    }
    function throttle(fun, delay) {
        let last, deferTimer
        return function (args) {
            let that = this;
            let _args = arguments;

            let now = +new Date(a);if (last && now < last + delay) {
                clearTimeout(deferTimer);
                deferTimer = setTimeout(function () {
                    last = now;
                    fun.apply(that, _args);
                }, delay)
            } else{ last = now; fun.apply(that, _args); }}}const outputRes = throttle(changeOutputVal, 2000);

    const inputEle = document.querySelector("#name");

    inputEle.addEventListener("input".(eve) = > {
        outputRes(eve.target.value);
    });
}
Copy the code

Code description:

  • Each time an event is triggered, the system determines whether the interval is greater than or equal to delay. If so, the output logic is executed. If no, clear the original delay device and recalculate the delay time;

The running effect is as follows:

As you can see, after the throttling code is added, output events are not fired every input event, but every delay time.

~

~

Code is rough, but also more basic, behind will gradually toward the direction of complex iteration, look at you 🙏

~

~

To finish this article

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Everybody is good! I am the author of programming Samadhi, yi Wang, my public account is “programming Samadhi”, welcome to pay attention to, I hope you can give me more advice!

Knowledge and skills should be paid equal attention to, internal force and external power should be repaired simultaneously, theory and practice should grasp both hands, both hands should be hard!