What is the anonymous number displayed during the settimeout function execution in the console?

Viewed 183

I tried executing settimeout() function using callback in javascript. An anonymous random number is displaying every time I use it(only in console). I wanna know what it is.

setTimeout(function() {   
      console.log("one");   
      setTimeout(function() {   
         console.log("two");   
         setTimeout(function() {   
            console.log("three");   
         }, 1000);   
      }, 1000);   
   }, 1000);   

Execution of the above code gives me a number in console:

Execution of the above code gives me a number in console

1 Answers

The console will display the result of the final expression (synchronously) evaluated above. Because setTimeout returns a number corresponding to the unique ID of the timeout, that is what the number you're seeing is - the ID of the outermost setTimeout.

(This ID is useful to have because it means you can then pass it to clearTimeout or clearInterval to clear the existing timeout or interval.)

You'd see the same sort of output with this code, where the ID is explicitly assigned to a variable, and then evaluated again on the last line:

outerTimeoutId = setTimeout(function() {   
  console.log("one");   
  setTimeout(function() {   
    console.log("two");   
    setTimeout(function() {   
      console.log("three");   
    }, 1000);   
  }, 1000);   
}, 1000);
outerTimeoutId;  // <-- results in some number being displayed in the console
Related