Make a summary every day, persistence is victory!

    /**
        @date 2021-07-13
        @description setInterval的delay
    */
Copy the code

One (sequence)

SetInterval is used to execute a function or piece of code repeatedly.

When using setInterval, you can pass in a delay as the interval of the timer, and execute a function or code segment after each delay millisecond. MDN describes this parameter as follows:

Is the number of milliseconds (one second equals 1000 milliseconds) of each delay after which each call to the function occurs. As with setTimeout, the actual delay may be slightly longer. This timer is measured in milliseconds (thousandths of a second) and causes a delay in the execution of a specified method or code segment. If this parameter is less than 10, the default value is 10.Copy the code

When I talked with someone about the parameter delay today, I said the minimum value was 10 according to the description on MDN, but it was not accepted, so I decided to verify the following.

How can I verify this? I want to use setTimeout to clear the setInterval timer and see how many times the setInterval is executed. The code is as follows:

let counter = 0;
const timer = setInterval(() => {
    counter++;
    console.log(counter);
}, 10);

setTimeout(() => {
    clearInterval(timer)
}, 1000);
Copy the code

In Chrome (Version: 91), the execution record is as follows:

delay   timer  last-print
1000    10     1
600     10     1
501     10     1
500     10     2
400     10     2
300     10     3
250     10     4
200     10     5(8)/4(2)
100     10     10
10      10     100
Copy the code

At present, it is normal, and the following records are as follows:

delay timer last-print 9 10 111 8 10 125(9)/124(1) 5 10 199(5)/198(3)/197(2) 1 10 250(6)/249(3)/247(1) 0 10 250 (9) / 248 (1) - 1 to 10, 250 (8) / 248 (1) / 246 (1)Copy the code

Chrome’s (version: 91) implementation of setInterval does not calculate the minimum value of delay based on 10, but about 4.

And we’ll talk about that next time when we talk about setInterval.