What is the default timeout in the setTimeout () method of a JavaScript Window object?

According to W3Schools, the required timeout parameter. But this can be called without a timeout parameter.

function eventHandler(e) { var t = setTimeout(function () { //clearTimeout(t); alert('Called'); }); } 
+6
source share
5 answers

HTML5 Timer spec says:

5) Let the timeout be the second argument of the method, or zero if the argument is omitted.

+15
source

If you do not want to set a timeout, just go 0

 setTimeout(function() { ... }, 0); 

Alternatively, you can simply omit the delay parameter and 0 assumed, however, for reliability (and general readability) it is best to pass something.

Note. does not guarantee that your code will be launched immediately. It queues the task when the user interface thread is available for processing.

+8
source

According to the HTML5 specification :

When the above methods should receive a timeout, they should start the following steps:

  • Let the timeout be the second argument to the method, or zero if the argument is omitted .
  • Apply the abstract operation ToString () to a timeout and give a timeout. [ECMA262]
  • Apply the abstract operation ToNumber () to a timeout and give a timeout. [ECMA262]
  • If timeout is an infinity value, a Not-a-Number (NaN) value or negative, let the timeout be zero.
  • Round the timeout to the nearest integer, and let the wait time be the result.
  • Return timeout.

Note that the specified zero timeout may not actually be delayed by zero milliseconds. See the setTimeout specification for more details.

+4
source

Why don't you check it out yourself? Documentation is always welcome, however you cannot win in real examples:

 var startTime = Date.now(); setTimeout(function () { var endTime = Date.now(); alert("timeOut was: " + (endTime - startTime) + "ms"); }); 

JSFiddle: http://jsfiddle.net/losnir/PbJBA/
Play with different timeout values.

Do not pass timeout arguments are almost the same as passing 0 . However, as you can see, the timeout is never 0 because your callback function will be queued and executed as soon as possible (based on your requested timeout value).

On average, it is about 5 ms, and if your user interface thread performs some intensive tasks or your processor is busy, it can be as high as a few hundred milliseconds, awful !

+3
source

Yes, you can do all this without giving time, but it's useless

 setTimeout( function() { alert("asdf"); }) 

he will shoot at the next tick

yes, but it will make this function asynchronous or queuing for later

 setTimeout(function() { alert("msg1"); }) alert("msg2"); 

in the above code msg2 is displayed.

+1
source

Source: https://habr.com/ru/post/951886/


All Articles