Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setInterval initiate when I'm only assigning it?

Tags:

javascript

I'm assigning to a variable, a function that uses setInterval, but I don't want the function to run until I call it. However, the function is running from just the assignment statement.

sessionClock = setInterval(function() {
  console.log("Hi")
}, 1000)

I have also tried like this:

sayHi = function() {
  console.log("Hi");
}

var sayHiStarter = setInterval(sayHi, 1000);

Both of these initiate the function and will log "Hi" to the console.

Why is it running on assignment? And what can do I do fix this?

like image 492
Chirpizard Avatar asked Jan 08 '23 05:01

Chirpizard


2 Answers

If you only want to bind a function to setInterval, but call it later, you can use bind:

var sessionClock = setInterval.bind(null, function() {
  console.log("Hi")
}, 1000);

//... later

var myInterval = sessionClock(); // start the timer

// ... later if you need to clear it

clearInterval(myInterval);

In principle, bind returns a new function that calls your original function (in this case, setInterval) with predefined arguments. So when you call sessionClock, that returned function is called. There a other aspects to bind, but they don't seem to apply in this context.

like image 96
nils Avatar answered Jan 09 '23 19:01

nils


The call to setInterval does not return a function, but an identification for the created interval. This id is used to remove the interval when you don't want it to execute anymore:

sessionClock = setInterval(function() {
  console.log("Hi")
}, 1000)

...

clearInterval(sessionclock);

What you want is something like this:

sessionClock = function () {
  return setInterval(function() {
      console.log("Hi")
    },
 1000);
}

//When needed
var intervalId=sessionClock();
like image 40
Pablo Lozano Avatar answered Jan 09 '23 19:01

Pablo Lozano