DEV Community

Cover image for setTimeout is not a part of JavaScipt, why ?
Aashish Panthi
Aashish Panthi

Posted on • Originally published at aashishpanthi.hashnode.dev

setTimeout is not a part of JavaScipt, why ?

Maybe you think setTimeout like this -: The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. it's true, but let's dive deeper.

There aren't any methods like setTimeout() or setInterval() in JavaScript. They are not provided by the JavaScript engine itself but they are provided by browser as part of the window object. Let's break it down:

If javascript doesn't provide setInterval() and setTimeout() but when we run our javascript code which also contains setTImeout it works perfectly fine. Yes, that's the real problem. Many people know how to use and they don't have any idea about what's going on under the hood. Before knowing about windows object, let's look at web APIs.

Web APIs

A browser can perform many tasks like getting user's location, turning on/off bluetooth, storage tasks, timer related tasks and many more. And we as a developers need these things. So, all these things can be accessed by JavaScript via Web APIs. That's it, now we have all these things inside one place and that place is window object.

Some web APIs:

  • localStorage
  • setTimeout()
  • console
  • DOM APIs
  • fetch()
  • location
  • alert()
  • and others

If setTimeout() is present inside window object then why we don't write like this:

window.setTimeout(() => console.log('Timer finished'), 1000 );
Enter fullscreen mode Exit fullscreen mode

Instead we write without window object:

setTimeout(() => console.log('Timer finished'), 1000 );
Enter fullscreen mode Exit fullscreen mode

window is a global object and setTimeout() is present inside global object(at global scope), so we can access setTimeout() without window object. Not only with setTimeout(), we don't need to write window object to access alert, localstorage, and other web APIs.

Far by we've discussed that the browser provides web APIs, so we can use the things likesetTimeout() but nodejs is not a browser. Then how is it possible to access setTimeout() in node. Well, we don't have window object available while working with node. But we can still access setTimeout(), let me tell you something at this point setTimeout() function in node works similar to window.setTimeout(), however they are not exactly same. Read more about this here.

Top comments (2)

Collapse
 
socr102 profile image
Eric

Excellent
Until now, I thought that the setTimeOut() is a function of JavaScript
Reading your post, I know more knowledge about this
Best

Collapse
 
aashishpanthi profile image
Aashish Panthi

Yes, I've been in the same position