[ Web Proxy ]
URL:
Viewing: https://ar.javascript.info/settimeout-setinterval [Back]  [Original]

: setTimeout setInterval
:
Light themeDark theme
DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek

: setTimeout setInterval

. (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);
Pass a function, but dont run it

() :

// 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);
Time goes on while alertis shown

So 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

( ) 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) and setInterval(func, delay, ...args) allow us to run the func once/regularly after delay milliseconds.
  • To cancel the execution, we should call clearTimeout/clearInterval with the value returned by setTimeout/setInterval.
  • Nested setTimeout calls are a more flexible alternative to setInterval, allowing us to set the time between executions more precisely.
  • Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(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 setTimeout or for setInterval (after 5th call) to 4ms. Thats for historical reasons.

.

:

  • .
  • .
  • .

( ) 300 1000 .

: 5

Write a function printNumbers(from, to) that outputs a number every second, starting from from and ending with to.

Make two variants of the solution.

  1. Using setInterval.
  2. Using nested setTimeout.

Using setInterval:

function printNumbers(from, to) {
  let current = from;

  let timerId = setInterval(function() {
    alert(current);
    if (current == to) {
      clearInterval(timerId);
    }
    current++;
  }, 1000);
}

// usage:
printNumbers(5, 10);

Using nested setTimeout:

function printNumbers(from, to) {
  let current = from;

  setTimeout(function go() {
    alert(current);
    if (current < to) {
      setTimeout(go, 1000);
    }
    current++;
  }, 1000);
}

// usage:
printNumbers(5, 10);

Note that in both solutions, there is an initial delay before the first output. The function is called after 1000ms the first time.

If we also want the function to run immediately, then we can add an additional call on a separate line, like this:

function printNumbers(from, to) {
  let current = from;

  function go() {
    alert(current);
    if (current == to) {
      clearInterval(timerId);
    }
    current++;
  }

  go();
  let timerId = setInterval(go, 1000);
}

printNumbers(5, 10);
: 5

In the code below theres a setTimeout call scheduled, then a heavy calculation is run, that takes more than 100ms to finish.

When will the scheduled function run?

  1. After the loop.
  2. Before the loop.
  3. In the beginning of the loop.

What is alert going to show?

let i = 0;

setTimeout(() => alert(i), 100); // ?

// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
  i++;
}

Any setTimeout will run only after the current code has finished.

The i will be the last one: 100000000.

let i = 0;

setTimeout(() => alert(i), 100); // 100000000

// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
  i++;
}


Web Proxy Viewer  |  New URL  |  Original Page