0

I am reading a book on javascript and there is a piece of code that I don't understand.

setTimeout( () => setTimeout(console.log, 0 , value *2), 1000);

What exactly is happening here? There are two setTimeout, and I think I only understand the inner one. I don't understand what () => function is doing? Can you explain?

I do follow:

setTimeout(console.log, 0 , value *2)

which is passing the argument 'value*2' to function/method console.log() after 0 milli seconds. I also understand that setTimeout() return the timeoutId.

I don't know the rest.

I see something similar with the following code:

let p1 = new Promise((resolve, reject) => resolve());
setTimeout(console.log, 0, p1);  //Promise <resolved>

Don't understand this either.

  • That's an arrow function. So, it's a `setTimeout` that takes 1 second to fire the arrow function within, which returns another `setTimeout` *(since there are no `{}`)*, which fires `console.log` after 0 milliseconds passing `value*2` to it. – StackSlave Jan 10 '20 at 01:28
  • Is this homework? I ask because, other than the educational explanation, this is pointless code - no reason to ever do this. You can get the same result with a single `setTimeout()`. – jfriend00 Jan 10 '20 at 01:33
  • Oh, I should state that `setTimeout` does return a `timeoutID`, but it fires the function that is passed to its first argument based on the second argument's milliseconds *(Asynchronously)*. All additional arguments are passed to your function argument. – StackSlave Jan 10 '20 at 01:37

2 Answers2

0

setTimeout( () => setTimeout(console.log, 0 , value *2), 1000); sets a timeout to... set a timeout. So after the the outer timeout finishes after 1 second, the inner function (() => {...} is an arrow function, which you can read as function() {...} for now) is called. This function sets another timeout with a delay of 0, which then calls console.log, passing value * 2 as a parameter. Thus, after 1 second, value * 2 is logged to the console.

With the Promise code, the line let p1 = new Promise((resolve, reject) => resolve()); creates a Promise which is immediately resolved. Thus on the next line when the promise is logged to the console, it shows Promise<resolved>.

see sharper
  • 11,505
  • 8
  • 46
  • 65
0
setTimeout(console.log, 0 , value *2)

is same as

setTimeout(function() { console.log(value *2) }, 0)

so

setTimeout( () => setTimeout(console.log, 0 , value *2), 1000);

means to set a timeout for one second, that will set another timeout for 0 second, and print value *2

let p1 = new Promise((resolve, reject) => resolve());
setTimeout(console.log, 0, p1);

means to print out the promise p1 after 0 second

Andus
  • 1,713
  • 13
  • 30