Understanding setInterval() and setTimeout() in JavaScript
Introduction
I am going to introduce you to two of my favorite built-in functions in JavaScript: setInterval()
and setTimeout()
. These are two awesome functions to know if you want an action to occur at a specific time or if you want something to continually happen such as a timer that increments or a fetch request.
setTimeout()
For setTimeout()
, it takes multiple parameters:
- A function which to execute on. (required)
- milliseconds — the program will wait the specified millisecond and then run. (optional)
- Additional parameters which are passed to the function. (optional)
Ok now let get into writing the actual code for this!
In the example above, we write the setTimeout
function first, where we pass in the parameters: the hello
function and 5000 milliseconds (5 seconds).
Then what happens it that after five seconds, we see the hello
function executes with the console.log
of “it’s been five seconds.”