1

I watched a youtube video about javascript in web browswer. They told about WebAPI when explaining how setTimeout() works.

In the case of node.js, I think node.js have no WebAPI.

How does setTimeout() works in NodeJS?

Byeongin Yoon
  • 3,233
  • 6
  • 26
  • 44
  • 2
    It might not be called WebAPI in their particular implementation but it is there, see their [Timers documentation](https://nodejs.org/api/timers.html) – Patrick Evans Sep 09 '18 at 12:12

1 Answers1

1

You call setTimeout with a function and delay. The code continues to run, and node eventually calls your function asynchronously.

This snippet shows the flow.

console.log('setTimeout will be called')
setTimeout( ()=>{console.log('hello')}, 1000 )
console.log('setTimeout was called')

setTimeout sets this to the global object.

If you use the function syntax, your this pointer will not be same as the this when calling, so you need to stash the context in a closure if you need it.

var that = this;
setTimeout(function(){// that !== this;}, 1000);
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78