The setInterval() method in JavaScript and make your own Interval Function

davidbell_xyz

David Bell

Posted on October 20, 2020

The setInterval() method in JavaScript and make your own Interval Function

setInterval() is a window method available to us. It takes two things:

  • A callback function
  • Time in milliseconds
setInterval(() => {
console.log('Hoopla')
}, 1000)
// Hoopla
// Hoopla…
Enter fullscreen mode Exit fullscreen mode

In the example an anonymous function () => is passed in. The time in milliseconds is passed at the very end }, 1000). Hoopla is printed to the console after 1 second has passed once rendered and again every second after.

You can also pass a function into setInterval.

const oneSec = () => {
console.log('Hoopla')
}
// Hoopla
// Hoopla…

setInterval(oneSec, 1000)
Enter fullscreen mode Exit fullscreen mode

The function oneSec() is ran after 1000 milliseconds then again every 1000 milliseconds.

A nuisance with setInterval() however is that is doesn’t run the function for the first time until the time passed in has passed.

For example the function below will wait 5 seconds before ‘Hoopla’ is first printed to the console. And then continue to run every 5 seconds after.

setInterval(() => {
console.log('Hoopla')

}, 5000)
Enter fullscreen mode Exit fullscreen mode

You can however create your own interval function that will begin immediately.

Make your own

const hoopla = () => console.log("Hoopla")

const myInterval = (func, time) => {
  func()
  return setInterval(hoopla, time)
}
myInterval(hoopla, 2000)
// Hoopla
// Hoopla…
Enter fullscreen mode Exit fullscreen mode

This functions takes a function as a parameter as well a time function, time. The function is immediately called and we return a regular setInterval. This is great because it works immediately with no day unlike a regular setInterval.

Let's connect

Connect on Twitter - davidbell_space

💖 💪 🙅 🚩
davidbell_xyz
David Bell

Posted on October 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related