Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The basic use

setTimeout/setInterval

grammar

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)

let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
Copy the code

Parameter Description:

  • Func | code: to perform the function or code string

  • Delay: indicates the delay before execution, expressed in milliseconds (1000 ms = 1 second). The default value is 0

  • Arg1, arg2… : A list of arguments to pass to the function (or code string) to be executed (not supported below IE9)

Example:

Common usage

With parameters

Note:

Pass in a function without parentheses ();

Because setTimeout expects a reference to a function. Test () is executing a function, so setTimeout is actually passing the result of the function’s execution

clearTimeout/clearInterval

Use to cancel setTimeout, setTimeout calls return a timer identifier, so cancel this write

let timerId = setTimeout(...) ; clearTimeout(timerId); let timerId = setInterval(...) ; clearInterval(timerId)Copy the code

Composite sample

// repeat every 1 second let timerId = setInterval(() => console.log(' execute '), 1000); SetTimeout (() => {clearInterval(timerId); The console. The log (' stop '); }, 3000);Copy the code

Zero delay usage of setTimeout

Method of use

SetTimeout (func, 0) or setTimeout (func)Copy the code

This allows funC to be executed as quickly as possible. But the program will only call it after the currently executing script has finished executing. That is, the function is scheduled to execute “as soon as” the current script completes execution.

Example:

The following code prints Hello and then World immediately

In the first line of code, we use the 0 delay of setTimeout, but it actually waits until the following print execution is complete. So print “Hello” first, then “World”.

Garbage collection and callback

When a function is passed setInterval/setTimeout, an internal reference is created for it and stored in the scheduler. This prevents the garbage collector (GC) from collecting the function even if it has no other references.

  • forsetInterval, the passed function will remain in memory untilclearIntervalIs invoked.

So: if a function refers to an external variable, then as long as the function exists, so does the external variable. They can take up more memory than the functions themselves. Therefore, when we no longer need the scheduling function, it is best to cancel it, even if it is a small function.

Difference between setInterval and setTimeout

The setTimeout function is deferred until an interval has elapsed

  • [Execute only once]

SetInterval allows us to run a function repeatedly, starting after an interval and then continuously repeating the function at that interval.

  • [Periodic execution at a given time at each interval]

If setInterval is not cleared, it will continue to run in a loop.

Problems with setInterval

SetInterval can be set to execute continuously after a certain period of time, but it actually only puts the event into the message queue. The actual execution time is not determined, so there are many different situations.

To illustrate, the following setInterval, which calls the func function every 100 milliseconds, may appear

[Case 1] : Func function execution time < 100 ms

That is, it finishes executing before the next 100 milliseconds.

Case 2: Func function execution time > 100 ms

When the next func function has been fired, the last one has not finished executing. At this point, the func waits in the queue (in this case, the event loop) until the last function has finished executing

[Situation 3] : The func function execution event is extremely long, and several funcs are triggered during execution. Guess what happened at this point? Is everyone lined up to be executed?

This is not the case in real time, as long as one function in the queue is detected, all others are ignored. In the figure below, callbacks at 300ms and 400ms are discarded, and once the first function is finished, the second function in the queue is executed, even if it is “out of date” for a long time.

Although the interval specified in setInterval is 100 milliseconds, it does not guarantee that the interval between calls is 100 milliseconds. In the above case, if the second function in the queue ends at 450 ms, it will continue to run the next round of func at 500 ms, meaning that the interval is only 50 ms instead of 100 ms. (If the function takes longer than delay sets each time, there will be no pause between calls at all.)

From the above examples, you can see that setInterval has several problems

  • When using setInterval, certain intervals are skipped;
  • Multiple timers may run consecutively.

Use setTimeout instead of setInterval

Let timerId = setTimeout(function run() {console.log(' execute '); timerId = setTimeout(run, 1000); }, 1000);Copy the code

The setTimeout above executes the next call immediately after the current function completes execution.

Nested setTimeout is much more flexible than setInterval. In this way, the next call can be executed based on the result of the current execution, so the next call can be different from the current one.


Reference:

Scheduling: setTimeout and setInterval


🎨 [thumbs up] [concerns] don’t get lost, more front-end dry goods waiting for you to unlock

Phase to recommend

👉 applet template template usage details

👉 the most complete CSS shadow summary

👉 call you to learn JavaScript addition, subtraction, multiplication and division!

👉 simply say JavaScript depth copy!