Why is setInterval triggered when I only assign it?

I am assigning a variable, a function using setInterval, but I do not want the function to execute until I call it. However, the function is performed only from the assignment statement.

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

I also tried like this:

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

var sayHiStarter = setInterval(sayHi, 1000);

Both of them initiate the function and will record "Hi" to the console.

Why does he work on appointment? And what can I fix it?

+4
source share
2 answers

If you 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);
Run codeHide result

, bind , ( setInterval) . , sessionClock, . bind, , , .

+8

setInterval , . , :

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

...

clearInterval(sessionclock);

, :

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

//When needed
var intervalId=sessionClock();
+1

Source: https://habr.com/ru/post/1615069/


All Articles