Javascript setinterval method

Learn how to use setInterval method in javascript.

Many times there comes a situation where you want to repeatedly execute a function after some delay. setInterval can be used to handle this type of problem.

Example

setInterval(function() => {
  console.log('I am called');
}, 1000);

//"I am called"
//"I am called"
//"I am called"
...
...

setInterval method calls itself repeatedly with a delay of a specified number of milliseconds.

Syntax

setInterval(function, milliseconds, param1, param2);

function: Required

The function that needs to be executed.

milliseconds: Optional

Interval in milliseconds on how often to wait before executing the function. The default is 10 if a value less than 10 is provided.

params: Optional

Extra parameters that need to be passed to the function will be executed (Works after IE9).

Return value

Each setInterval method returns a numeric ID that is assigned to it. It can be used to stop the timer.

setInterval(function() => {
  console.log('I am called');
}, 1000);

//"I am called"
//"I am called"
//"I am called"
...
...

setInterval function is executed repeatedly. If you want to call something only once then use setTimeout.


Calling predefined function

 let start = 0;

 let count = (count, message) => {
   console.log(`${message} is ${count}`);
 }

 setInterval(function(){
   count(start++, 'count');
 }, 1000);

//count is 0
//count is 1
//count is 2
...
...

Passing params separately

 let start = 0;

 let count = (count, message) => {
   console.log(`${message} is ${count}`);
 }

 setInterval(count, 1000, start++, 'count');

//count is 0
//count is 0
//count is 0
...
...

Here the start is not getting increment because the value is accessed from the global scope. Also this method won’t work in IE9 and less. Better use above method only.


Handling this

Handling this with setInterval was not so easy before, We had to use a workaround for that.

let increment = {
  count: 1,
  start: function(){
    setInterval(function(){
      console.log(that.count++);
    }, 1000)
  }
}

increment.start();
//NaN
//NaN
//NaN
...

Now this inside the setInterval is referring to its context but we want to access the parent’s this. Incrementing the undefined value is resulting in NaN.

So we assign the parent’s this to another variable and use it.

let increment = {
  count: 1,
  start: function(){
    //Assign this to a variable that
    var that = this;
    setInterval(function(){
      console.log(that.count++);
    }, 1000)
  }
}

increment.start();
//1
//2
//3
...

But with introduction of => function in ES6 we can handle this easily.

let increment = {
  count: 1,
  start: function(){
    setInterval(() => {
      console.log(this.count++);
    }, 1000)
  }
}

increment.start();
//1
//2
//3
...

Clearing setInterval

let start = setInterval(() => {
   console.log('I just started');
   clearMe();
}, 2000);

let clearMe = () => {
   clearInterval(start);
}

//"I just started"

clearInterval method stops the timer set by the setInterval. It takes setInterval ID as input which is required.


How to use setInterval

There are many times where setInterval method can be used.

Here is the one situation like this. You want to create a clock and keeping it running by showing each seconds.

To achieve this you can simply use the setInterval method and print the time at 1 second interval.

function clock() {
  let date = new Date();
  let h = date.getHours();
  let m = date.getMinutes();
  let s = date.getSeconds();

  console.log(`${h} : ${m} : ${s}`); 
}

setInterval(() => {
  clock();
}, 1000);

//"18 : 24 : 56"
//"18 : 24 : 57"
//"18 : 24 : 58"
...
...

Comments

Leave a Reply

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