This is the sixth day of my participation in the August Text Challenge.More challenges in August

directory

  1. Image stabilization (debounce)
  2. The throttle (throttle)
  3. The difference between anti-shake and throttling

Last week, I wrote a form, but I didn’t look carefully at the mask configuration of Toast, thinking that it was on by default as before. However, it was actually closed, and because I was lazy and didn’t add anti-shake throttled to the button, users submitted multiple data repeatedly……

Silently took out a small notebook this to record enemy: who closed my mask button must remember to add anti – shake throttling!!

All right, back to the point, let’s review the throttling.

1, the image stabilization

Shock proof, Debounce. This concept first comes from the camera, and now the popular camera anti-shake principle is divided into many kinds, including lens anti-shake, body anti-shake, etc. The anti-shake in our code is similar to software anti-shake:

“It continuously detects hand shaking: if your hand is shaking, the phone won’t take a picture even if you have pressed the shutter, until it detects a moment when your hand is relatively still. It automatically pressed the shutter! So this isn’t an active anti-shake feature, it’s just an active ‘hands-free time’ to take a picture. It’s good for landscapes, not people, because there’s no way to capture them.” [1]

Take another example of anti-shaking in life, those who have taken the elevator should have felt that the elevator always has to wait for a short period of time before closing the door. If someone enters before the elevator door closes, the elevator will reopen the door and then close it for a short period of time. If more people enter the elevator before it closes, the elevator will wait for the last person to enter and then wait a short time before closing.

The so-called anti-shake, is in the event triggered after the delay n seconds to execute; If the event is triggered again within n seconds, the timer is reset and execution is delayed for n seconds.

Code implementation:

function debounce(fn, delay) {
    let timer = null;
    return() = > {if (timer) {
            // reset the timer
            clearTimeout(timer);
        }
        const context = this;
        timer = setTimeout(() = >{
            fn.apply(context, arguments);
            clearTimeout(timer); }, delay); }}let count = 0;
const play = debounce(() = >{
    console.log(count++);
},
3000);
Copy the code

Online: jsrun.net/Tr8Kp/edit

The throttle

Throttle, throttle Definition of engineering thermodynamics terms: the flow of fluid in the pipeline through the channel cross-section suddenly reduced valve, slit and orifice after the phenomenon of pressure reduction is called throttling. [2]

In simple terms, the actual flow is limited through the valve. For example, if the user initiates 1000 requests within 10 seconds, only 1 request will actually be sent to the server within 10 seconds after throttling, and no other requests will be sent.

Throttling is the execution of an event only once in a period of time, no matter how many times the event is triggered.

Code implementation:

// Timestamp version
function throttle(fn, delay) {
    let isRun = false;
    let startTime = Date.now();
    return function() {
        let now = Date.now();
        if (now - startTime > delay) {
            // Delay execution
            // const context = this
            // fn.apply(context, arguments)
            startTime = now isRun = false;
        }


        if (isRun) return;


        isRun = true;


        // Execute immediately
        const context = this 
        fn.apply(context, arguments)}}let count = 0;
const play = throttle(() = >{
    console.log(count++);
},
3000);
Copy the code

Online: jsrun.net/Wr8Kp/edit

// Timer version
function throttle(fn, delay) {
    let timer = null
    return() = > {if (timer) return;
        const context = this;
        // Execute immediately
        fn.apply(context, arguments);
        timer = setTimeout(() = > {// Delay execution
            // fn.apply(context, arguments);
            clearTimeout(timer);
            timer = null; }, delay); }}let count = 0;
const play = throttle(() = >{
    console.log(count++);
},
3000);
Copy the code

Online: jsrun.net/Lr8Kp/edit

The difference between anti-shake and throttling

Take a look at the following test code:

let t = 0;
/** click every second. It will never trigger unless you stop automatically clicking */
let interval = null;
start();
function start() {
    if(! interval) { interval =setInterval(() = >{
            t++;
            console.log("Trigger" + t + "Time");
            play();
        },
        1000); }}function stop() {
    console.log("Hit stop trigger");
    clearInterval(interval);
    interval = null;
}
Copy the code

This test code will trigger the play() method every second. According to the above code, if the delay is 3s, what will be the output result?

Debounce

Throttle output:

The difference between:

  • Because the anti-shake has been triggered constantly, each trigger will be re-timed, and the delay of 3S cannot be reached all the time, so it cannot be executed all the time. Execute only after the trigger is stopped (output count value 0 after 3s of last trigger);
  • Throttling is performed every 3s; There may be multiple triggers in 3s, but it will only be executed once in 3s.

References:

[1] https://m.sohu.com/a/288759421_419981
[2] https://baike.baidu.com/item/ throttling / 13128947? Fr = Aladdin