setTimeout is not a part of JavaScipt
setTimeout and setInterval are not actually included in javascript - let's understand this.
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 );
Instead we write without window
object:
setTimeout(() => console.log('Timer finished'), 1000 );
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.