JavaScript: pass a variable from one function to another using setInterval ()?

So, I have a function that executes a function execution loop, for example:

function(f){
  var variable;
  for(z = 0; z < 10; z++){
    variable = "cool";         
    setInterval(f)
  }

Btw, the actual function of MUCH is more complex than that, but it is the same theory. I want to be able to execute a function in the argument f and set some variables (e.g. a variable) so that this function can use them, in general this is the idea:

function say(f){
   var variable = "hey";
   setInterval(f);
}
say(function(){
   alert(variable)
});

Here you need to get a warning window that says. This is a theory, but it will not work:

The variable "variable" is not defined

The browser will probably just ignore the error and notify undefined.

But anyway, how can I “transfer” a variable without changing its volume .

+3
4

, call apply:

function say(f){
   var variable = "hey";
   setInterval(function() { 
       f.call(variable); // set the context
   }, 1000);
}
say(function(){
    alert(this);
});
+3

JavaScript , :

var x = 0;
setInterval(function() {
   //do something with x
}, 1000);

:

function say(f){
   var variable = "hey";
   setInterval(function() { 
       f(variable); //invoke the say function passed-in "f" function, passing in "hey"
   }, 1000);
}
say(function(arg){
    //arg will be "hey"
    alert(arg);
});

setInterval , - ( ), - .

+7

, - , . :

function say(f){
   var variable = "hey";
   setInterval( function(){ f(variable) }, 500 );
}
say(function(yyy){
   alert(yyy);
});
+1
function say(f){
  var variable = "hey";
  setInterval(function(){
    f.call(null, variable);
  }, 1000);
}
say(function(variable){
   alert(variable)
});

Using the call method in a function.

+1
source

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


All Articles