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

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);

 Copy

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);

 Copy

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', '!');

 Copy

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);

 Copy

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.

Output1
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);

 Copy

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);

 Copy

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)

 Copy

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.

ConclusionF

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.

(Visited 1 times, 1 visits today)
Jasca
Author: Jasca

Share This Post
Have your say!
00

Customer Reviews

5
0%
4
0%
3
0%
2
0%
1
0%
0
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Thanks for submitting your comment!