Pass parameters in setInterval function

Pass parameters in setInterval function

Please advise how to pass parameters into a function called using setInterval.
My example setInterval(funca(10,3), 500); is incorrect.

Solutions/Answers:

Solution 1:

You need to create an anonymous function so the actual function isn’t executed right away.

setInterval( function() { funca(10,3); }, 500 );

Solution 2:

now with ES5, bind method Function prototype :

setInterval(funca.bind(null,10,3),500);

Reference here

Solution 3:

Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

The syntax in your question uses eval, which is not recommended practice.

Solution 4:

You can pass the parameter(s) as a property of the function object, not as a parameter:

var f = this.someFunction;  //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);

Then in your function someFunction, you will have access to the parameters. This is particularly useful inside classes where the scope goes to the global space automatically and you lose references to the class that called setInterval to begin with. With this approach, “parameter2” in “someFunction”, in the example above, will have the right scope.

Solution 5:

You can use an anonymous function;

setInterval(function() { funca(10,3); },500);

Solution 6:

     setInterval(function(a,b,c){

          console.log(a + b +c);  

      }, 500, 1,2,3);

           //note the console will  print 6
          //here we are passing 1,2,3 for a,b,c arguments
         // tested in node v 8.11 and chrome 69