. (scheduling a call).
:
-
setTimeout. -
setInterval.
. Node.js .
setTimeout
:
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
:
func|code- . , () .
delay- The delay before run, in milliseconds (1000 ms = 1 second), by default 0.
arg1,arg2- ( IE9-)
sayHi() :
function sayHi() {
alert('Hello');
}
setTimeout(sayHi, 1000);
:
function sayHi(phrase, who) {
alert( phrase + ', ' + who );
}
setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John
If the first argument is a string, then JavaScript creates a function from it.
So, this will also work:
setTimeout("alert('Hello')", 1000);
But using strings is not recommended, use arrow functions instead of them, like this:
setTimeout(() => alert('Hello'), 1000);
() :
// wrong!
setTimeout(sayHi(), 1000);
setTimeout sayHi() setTimeout. sayHi() undefined ( ) .
clearTimeout
setTimeout timerId .
The syntax to cancel:
let timerId = setTimeout(...);
clearTimeout(timerId);
In the code below, we schedule the function and then cancel it (changed our mind). As a result, nothing happens:
let timerId = setTimeout(() => alert('never happens'), 1000);
alert(timerId); // timer identifier
clearTimeout(timerId);
alert(timerId); // same identifier (doesn't become null after canceling)
alert ( ) . . Node.js .
Again, there is no universal specification for these methods, so thats fine.
HTML5 ( ) .
setInterval
setInterval setTimeout:
let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
. setTimeout .
clearInterval(timerId) .
:
// repeat with the interval of 2 seconds
let timerId = setInterval(() => alert('tick'), 2000);
// after 5 seconds stop
setTimeout(() => {
clearInterval(timerId);
alert('stop');
}, 5000);
alertis shownSo if you run the code above and dont dismiss the alert window for some time, then the next alert will be shown immediately as you do it. The actual interval between alerts will be shorter than 2 seconds.
Nested setTimeout
There are two ways of running something regularly.
setInterval. setTimeout :
/** instead of:
let timerId = setInterval(() => alert('tick'), 2000);
*/
let timerId = setTimeout(function tick() {
alert('tick');
timerId = setTimeout(tick, 2000); // (*)
}, 2000);
setTimeout ( (*)).
setTimeout setInterval. .
10 20 40
:
let delay = 5000;
let timerId = setTimeout(function request() {
...send request...
if (request failed due to server overload) {
// increase the interval to the next run
delay *= 2;
}
timerId = setTimeout(request, delay);
}, delay);
And if the functions that were scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later.
setTimeout setInterval.
. setInterval:
let i = 1;
setInterval(function () {
func(i++);
}, 100);
setTimeout :
let i = 1;
setTimeout(function run() {
func(i++);
setTimeout(run, 100);
}, 100);
func(i++) 100 setInterval:
Did you notice?
func setInterval !
func .
func 100 .
func : .
delay .
setTimeout :
setTimeout (100 ).
Thats because a new call is planned at the end of the previous one.
( ) setInterval/setTimeout .
// the function stays in memory until the scheduler calls it
setTimeout(function() {...}, 100);
For setInterval the function stays in memory until clearInterval is called.
. . .
setTimeout
: setTimeout(func, 0) setTimeout(func).
func .
So the function is scheduled to run right after the current script.
, Hello, World:
setTimeout(() => alert('World'));
alert('Hello');
0 "Hello" "World".
: .
. HTML5 standard HTML5: ..
. setTimeout times. :
let start = Date.now();
let times = [];
setTimeout(function run() {
times.push(Date.now() - start); // remember delay from the previous call
if (start + 100 < Date.now()) alert(times); // show the delays after 100ms
else setTimeout(run); // else re-schedule
});
// an example of the output:
// 1,1,1,1,9,15,20,24,30,35,40,45,50,55,59,64,70,75,80,85,90,95,100
( ) 9, 15, 20, 24. .
setInterval setTimeout : setInterval(f) f .
( ) .
For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like setImmediate for Node.js. So this note is browser-specific.
- Methods
setTimeout(func, delay, ...args)andsetInterval(func, delay, ...args)allow us to run thefunconce/regularly afterdelaymilliseconds. - To cancel the execution, we should call
clearTimeout/clearIntervalwith the value returned bysetTimeout/setInterval. - Nested
setTimeoutcalls are a more flexible alternative tosetInterval, allowing us to set the time between executions more precisely. - Zero delay scheduling with
setTimeout(func, 0)(the same assetTimeout(func)) is used to schedule the call as soon as possible, but after the current script is complete. - The browser limits the minimal delay for five or more nested calls of
setTimeoutor forsetInterval(after 5th call) to 4ms. Thats for historical reasons.
.
:
- .
- .
- .
( ) 300 1000 .
<code><pre>10 (plnkr, JSBin, codepen)