AppDividend
Latest Code Tutorials

Javascript Timer | setTimeout | setInterval | clearTimeout

0

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

Javascript Timer Example

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

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

#Javascript setTimeout() Method

When we are writing the JavaScript code, we might want to delay the execution of the function. The setTimeout() method expects the two arguments: a reference to a callback function and the delay in milliseconds. 

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

The 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 and add the above code and run the file using the following command.

node server

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

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

// server.js

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

setTimeout(app, 2000);

#Cancelling 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 first, it will try to execute the appTimer, but it has a delay of 1000 milliseconds. So it will go for the next setTimeout function. Now, remember, it has a 600 milliseconds delay, so it will execute first and call the clearTimeout function.

So 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. 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() Method

The setInterval() method repeats the given function at every given 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 value and print it to the console every second.

Finally, Javascript Timer Example | setTimeout | setInterval | clearTimeout is over.

Leave A Reply

Your email address will not be published.

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