Jimmy Hogerty
Jimbos1ice Development

Jimbos1ice Development

Controlling JavaScript's setInterval Method

Same applies to setTimeout!

Jimmy Hogerty's photo
Jimmy Hogerty
·Jan 15, 2022·

1 min read

Controlling JavaScript's setInterval Method

Assigning Function Invocations to Variables

var a = setInterval(function(){console.log('Did I start yet?'), 2000);

What happens if we open our Chrome console and paste this in?

It's a bit deceiving, but we're assigning variable a to a function invocation. It's similar to running the following code:

var b = function(){console.log('Did I log myself?')};

var c = b();

Notice how, right after we declare var c = b(), we invoke variable b.

Despite us immediately invoking setInterval, we're able to stop it whenever we like with clearInterval:

var a = setInterval(function(){console.log('Did I start yet?'), 2000);

clearInterval(a);

Excellent! We can control when our setInterval ends. But we don't have control over where it begins. So how do we control this? Let's look at a scenario where we're using objects and methods:

var obj = {
  aKey: setInterval(() => console.log('hi'), 2000)
}

Running this code would also invoke setInterval. So how do we control when our setInterval begins?

var obj = {
  aKey: function() {
  return obj.interval = setInterval(() => console.log('hi'), 2000);
  }
}

// START INTERVAL: Begins setInterval with its ID set to obj.interval
obj.aKey();

// STOP INTERVAL: Clears the interval we set
clearInterval(obj.interval)

Full setInterval Start/Stop Control Achieved!

There you have it. I hope this brief write-up was helpful!

 
Share this