Timer setTimeout() and setInterval() in js

JavaScript timers, sometimes called "timers", are used to perform certain tasks after a specified time has elapsed, similar to an alarm clock in our lives.

In JavaScript, we can use timers to delay the execution of some code, or to repeatedly execute some code at fixed intervals. For example, you can use a timer to regularly update advertisements on the page or display a real-time clock.

There are two ways to set timers in JavaScript, namely setTimeout() and setInterval() . The differences between them are as follows:

method effect
setTimeout() After the specified time (in milliseconds), execute some code, the code will only be executed once
setInterval() Execute some code repeatedly according to the specified cycle (in milliseconds) , the timer will not stop automatically unless the clearInterval() function is called to manually stop or close the browser window

The details are as follows:

setTimeout()

Common syntax:

// 单次定时器,只能执行一次
setTimeout(function () { },time);
 // - 参数1:function 必需。函数,过time时间之后执行的业务逻辑,可写成箭头函数()=>{}的形式
 // - 参数2:time 可选。执行或调用 function 需要等待的时间,以毫秒ms计。默认为 0
 
// 清除setTimeout单次定时器
clearTimeout(定时器名称);

Note: When time takes the default value of 0, it means to execute "immediately", or as soon as possible. In either case, the actual delay may be longer than the expected (time milliseconds) value.

The reason why the actual delay is longer than the set value: the minimum delay time

In the browser, the minimum interval for each timer call of setTimeout()/setInterval() is 4ms , which is usually caused by function nesting (the nesting level reaches a certain depth of 5 layers ), or because setInterval has been executed Caused by the blocking of the callback function of , different browsers have different situations in which this minimum delay occurs

setInterval()

Common syntax:

// 循环定时器,不停歇,每过一段时间time,执行一次。
 setInterval(function () { },time);
// 参数同setTimeout
 
// 清除setInterval循环定时器
clearInterval(定时器名称);

The call function in setTimeout() and setInterval() is also called the callback function callback. Ordinary functions are called directly according to the order of the code. And this function needs to wait for time, and then call this function when the time is up, so it is called a callback function.

Delay constraints: Timers are nestable; this means that a call to setInterval() can be embedded in the callback of setInterval() to create another timer, even if the first timer is still running. To mitigate this potential impact on performance, browsers will automatically enforce a minimum interval of 4 milliseconds for timers once timers are nested more than 5 levels deep . If you try to set the delay in deeply nested calls to setInterval() to a value smaller than 4ms, it will be fixed at 4ms.

Guess you like

Origin blog.csdn.net/qq_42691298/article/details/129254641