Are variables automatically executed when declared?

0

For example, if we save a setInterval() to a variable, does it already run automatically even though that variable has not been called anywhere?

Example:

let i = 0;
let myInterval = setInterval(function(){
  console.log(i++)
  if(i > 10){
    clearInterval(myInterval)
  }
},1000)

I did not even call myInterval nowhere and it is already running ...

Are variables already automatically executed when declared?

The question is only because in the function we have to call it somewhere, do you understand?

Is this true for JS or for all languages?

    
asked by anonymous 06.08.2018 / 21:10

3 answers

5

Variables are states and not actions, so it does not make sense to talk about running variables.

What you did was call setInterval() , this is enough. As argument passed an action, as he expects. Without the variable working the same way, it is completely useless in this code:

let i = 0;
setInterval(function(){
  console.log(i++);
},1000)
    
06.08.2018 / 21:14
0

This is because you did not declare the variable with the function, only the return of this. Your code should be:

let i = 0;
let myInterval = function(){
    setInterval(function(){
      console.log(i++)
      if(i > 10){
        clearInterval(myInterval)
      }
    },1000)
}

So, just by explicitly calling:

myInterval()

The setInterval will be executed.

    
07.08.2018 / 01:57
0

You are saving in the variable the return of the setInterval function, you can store the function in this way:

let interval = setInterval

And then you execute calling the function name plus the parentheses

interval()

let interval = setInterval
let c = null
let i = 0

let funToExecute = function() {
    console.log(i)
    i++
    if (i > 10) {clearInterval(c)}
}

c = interval(funToExecute, 1000)
    
08.08.2018 / 18:13