Javascript Timer | setTimeout | setInterval | clearTimeout

0
21
setTimeout and setInterval clearTimeout example tutorial

In Javascript, we need to use the time interval functions if we want to delay code execution. These time intervals are called timing events. This is because the block of JavaScript code is executed synchronously. But some JavaScript native functions (timers) allow us to delay the execution, and we can create an async kind of behavior.

Javascript Timer

The two key methods to use in Timer with JavaScript are:

  1. setTimeout(function, milliseconds)
    Executes the function after waiting for the specified number of milliseconds.
  2. setInterval(function, milliseconds)
    Same as the setTimeout(), but repeats execution of the function continuously.

JavaScript setTimeout

The setTimeout() method is a built-in JavaScript method that calls a function after several milliseconds. The setTimeout() method expects two arguments: a reference to a callback function and the delay in milliseconds. 

The job of setTimeout() method is straightforward. You specify the callback function to execute later and the value expressing how then you want it to run in milliseconds:

A simple example is the following.

setTimeout(() => {
  console.log('Run after two seconds')
}, 2000);

Now, for this example, we will use Node.js as a platform. So create one server.js file, add the above code, and run the file using the following command.

node server

You will see the output in the console after two seconds.

We can also use the function by its name and not an inline function like the above example. 

// server.js

function app() {
  console.log('Run after two seconds');
}

setTimeout(app, 2000);

Canceling a timer

The setTimeout() method returns a timer id that can then be passed to the global clearTimeout() method to cancel the timeout. Take the following example.

// server.js

function app() {
  console.log('Clear timeout example');
}

const appTimer = setTimeout(app, 1000);

setTimeout(() => {
  clearTimeout(appTimer);
}, 600);

Here, you can see that it will try to execute the appTimer, but it has a delay of 1000 milliseconds. So it will go for the next setTimeout function. Remember, it has a 600 milliseconds delay, so it will execute first and call the clearTimeout function.

So the clearTimeout() function takes an argument which is the appTimer. So it will cancel that previous 1000 milliseconds timer, and we see nothing in output.

We can check it manually by logging the second timeout event. But, first, update the following code inside the server.js file.

// server.js

function app() {
  console.log('Clear timeout example');
}

const appTimer = setTimeout(app, 1000);

setTimeout(() => {
  console.log('Cancel the setTimeout event');
  clearTimeout(appTimer);
}, 600);

Output

Javascript Timer Example Tutorial | setTimeout | setInterval | clearTimeout

Javascript setInterval

The setInterval() is a built-in JavaScript method that repeats the given function at every time interval. The first parameter is a function that needs to be executed, and the second parameter indicates the length of a time interval between each execution.

// server.js

let count = 0;

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

setInterval(increment, 1000);

Output

Javascript setTimeout example

The difference is that setInterval calls the callback function repeatedly with the specified delay in-between the calls. In the following example, we increment the value and print it to the console every second.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.