1

Run in console next code

setTimeout(function(){
   console.log(1);
}, 2);
console.log(2);
setTimeout(function(){
   console.log(3);
}, 1);

Why 4 values when has only 3? console

4
  • 2
    That code does not produce 4 values. Here's proof that it doesn't. Something else is printing out the 20. For future reference, do not include console output or any other text as images. Copy the text and include it in your question. For one, it makes it more searchable. Commented May 31, 2017 at 13:50
  • You can tell something else is outputting 20 by the little arrow next to it. Commented May 31, 2017 at 13:51
  • 2
    You console log shows something called a "return value". The return value of a timeout is the ID for that timeout. Commented May 31, 2017 at 13:51
  • It is the setTimeout reference, try var t = setTime.. then print console.log(t). Now, why it shows only the first idk. Commented May 31, 2017 at 13:52

1 Answer 1

3

You get a return value of setTimeout in the console.

The returned timeoutID is a numeric, non-zero value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

It may be helpful to be aware that setTimeout() and setInterval() share the same pool of IDs, and that clearTimeout() and clearInterval() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code

console.log(setTimeout(function(){
   console.log('#' + 1);
}, 2));
console.log('#' + 2);
console.log(setTimeout(function(){
   console.log('#' + 3);
}, 1));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.