Tutorial

How To Schedule Tasks With setTimeout() and setInterval() in JavaScript

Updated on December 23, 2020
Default avatar

By Alligator.io

How To Schedule Tasks With setTimeout() and setInterval() in JavaScript

Introduction

Both setTimeout() and setInterval() are built-in methods of the global object on the Document Object Model to schedule tasks at a set time.setTimeout() calls a passed-in function once after a specified delay, while setInterval() invokes one continuously at a designated time. As JavaScript is a singly-threaded language, both methods allow your code to run asynchronously.

In this article, you will learn about how to implement setTimeout() and setInterval() in your JavaScript project.

Applying setTimeout()

The setTimeout() method accepts two arguments: a callback function and a delay in milliseconds, and calls the function once.

In your index.js file, implement a setTimeout() method and pass in an anonymous function as the first argument, and a number in milliseconds as the second argument:

index.js
setTimeout(() => {
  console.log('Hello World!');
}, 1000);

After a delay of 1000 milliseconds (which is equivalent to one second), the console will print out the string Hello World!.

You may also define a function globally and pass into setTimeout() as the first argument.

In your index.js file, define a function in the global space and pass in the function label within the setTimeout() method:

index.js
function greeting() {
  console.log('Hello World!');
}

setTimeout(greeting, 1000);

After a delay of one second, the console will log out the string Hello World!.

Note: You should not invoke the function you pass into setTimeout(). Instead, insert the function label as the first argument.

The setTimeout() method can take additional, optional arguments, and pass these into the callback function after the specified delay. In your index.js file, apply additional arguments into your setTimeout() method:

index.js
function animal(animalName, punctuation = '.') {
  const name = animalName.charAt(0).toUpperCase() + animalName.slice(1);

  console.log(`${name}`${punctuation});
}

setTimeout(animal, 2500, 'shark', '!');

After 2.5 seconds, the console will print out the message, Shark!. The addtional argument in your setTimeout() method overrides the default argument in the animal callback function.

Now that you’ve reviewed the setTimeout() method, let’s look at another way to create asynchronous calls in JavaScript.

Applying setInterval()

Similar to setTimeout(), the setInterval() method accepts two arguments: a callback function and a delay in milliseconds. The method also accepts additional arguments to pass into the callback function. The difference is that the setInterval() method invokes the callback function regularly with a specified delay between calls.

In your index.js file, define a function that increments a number and logs the value:

index.js
let i = 0;

function increment() {
  i++;
  console.log(i);
}

setInterval(increment, 1000);

The increment callback function passed into your setInterval() method will run your code repeatedly every one second, and print each succeeding number to the console.

Output
1 2 3 ...

As setInterval() applies a delay for each successive call to the callback function, let’s consider when to use the method over setTimeout().

Using setTimeout() Recursively

To have more control on defining the start of your specified delays, you can utilize the setTimeout() method recursively instead of setInterval(). The recursive approach to setTimeout() allows your tasks to have full control on when your delay starts.

In your index.js file, define a function that increments a number and apply a recursive setTimeout() method:

index.js
let i = 0;

function increment() {
  i++;
  console.log(i);
}

let timer = setTimeout(function myTimer() {
  increment();
  timer = setTimeout(myTimer, 1000);
}, 1000);

Notice how you define a callback function, myTimer within the body of the first invocation to the setTimeout() method. The variable timer reassigns its value to a second call of the setTimeout() method, and creates a recursive approach when invoking the method and passing the myTimer function as the first argument. With each recursive call, the console will log an incremented number with no delay, as both setTimeout() methods have a second argument of 1000.

Now that you’ve analyzed approaches to integrate both methods, let’s examine how to terminate a call.

Using clearTimeout() and clearInterval()

To cancel a setTimeout() method, you can resort to the clearTimeout() method passed within the body of your setTimeout() call. The clearTimeout() method accepts a callback function as an argument.

In your index.js file, define a function and pass in the clearTimeout() method within the body of your call to setTimeout():

index.js
function animal(animalName, punctuation = '.') {
  const name = animalName.charAt(0).toUpperCase() + animalName.slice(1);

  console.log(`${name}${punctuation}`);
}

const animalTimer = setTimeout(animal, 800, 'shark', '!');

setTimeout(() => {
  clearTimeout(animalTimer);
}, 250);

The variable animalTimer assigns its value a call to the setTimeout() method with your animal function as the callback and a second argument with a delay of 800 milliseconds.

Your second call to the setTimeout() method accepts the clearTimeout() method within the body of an anonymous function, and a delay of 250 milliseconds. As you set your clearTimeout() method, no value will log into the console as both the method call and the delay of 250 milliseconds cancels the value in the animalTimer variable. Increasing the number of milliseconds within the second call to the setTimeout() method will log values into the console and terminate an instance once the delay fulfills.

To cancel a setInterval() method, you can apply the clearInterval() method. Similarly to clearTimeout(), the clearInterval() method accepts a callback function as an argument.

In your index.js file, use the clearTimeout() method within the body of your call to setInterval():

index.js
let i = 0;

function increment() {
  i++;
  console.log(i);
}

const incrementTimer = setInterval(increment, 1000);

setInterval(() => {
  clearInterval(incrementTimer);
}, 3000)

Here, the variable incrementTimer() stores a call to setInterval() as its value. The second call to your setInterval() method defines an anonymous function and sets a delay of 3000 milliseconds. The call also passes in the clearInterval() method with the incrementTimer variable as an argument. After 3000 milliseconds, the console will log the incremented values and the setInterval() method will terminate once the delay fulfills.

Conclusion

In this article, you learned that as JavaScript reads code line by line, the setTimeout() and setInterval() methods provide you a solution to run your code asynchronously, and time your function calls at your discretion.

setInterval() will continuously execute over a specified amount of time. setTimeout() executes once, but can be used recursively to wait for a callback to indicate when it should wait to execute again. The recursive approach is useful for situations that require ensuring a task that may take longer than the delay finishes before running again.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
2 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Hello, I’m using setTimeout a lot in my app, which is delpoyed as an App on Digital Ocean. Is it possible, that old setTimeouts are not cleared on redeploy and executed even after version update?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel