Understanding setInterval() and setTimeout() in JavaScript

R.
Webtips
Published in
3 min readAug 28, 2020

--

Photo by Ocean Ng on Unsplash

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:

  1. A function which to execute on. (required)
  2. milliseconds — the program will wait the specified millisecond and then run. (optional)
  3. 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.”

Stop Execution of setTimeout()

--

--

R.
Webtips
Writer for

Software Developer && Political Enthusiast