[javascript] 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.

This question is related to javascript parameters setinterval

The answer is


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

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

I have had the same problem with Vue app. In my case this solution is only works if anonymous function has declared as arrow function, regarding declaration at mounted () life circle hook.


     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

setInterval(function,milliseconds,param1,param2,...)

Update: 2018 - use the "spread" operator

_x000D_
_x000D_
function repeater(param1, param2, param3){_x000D_
   alert(param1);_x000D_
   alert(param2);_x000D_
   alert(param3); _x000D_
}_x000D_
_x000D_
let input = [1,2,3];_x000D_
setInterval(repeater,3000,...input);
_x000D_
_x000D_
_x000D_


I know this topic is so old but here is my solution about passing parameters in setInterval function.

Html:

var fiveMinutes = 60 * 2;
var display = document.querySelector('#timer');
startTimer(fiveMinutes, display);

JavaScript:

function startTimer(duration, display) {
    var timer = duration,
        minutes, seconds;

    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        --timer; // put boolean value for minus values.

    }, 1000);
}

     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

const designated = "1 jan 2021"

function countdown(designated_time){

    const currentTime = new Date();
    const future_time = new Date(designated_time);
    console.log(future_time - currentTime);
}

countdown(designated);

setInterval(countdown, 1000, designated);

There are so many ways you can do this, me personally things this is clean and sweet.


You can use an anonymous function;

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

now with ES5, bind method Function prototype :

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

Reference here


Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

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


Another solution consists in pass your function like that (if you've got dynamics vars) : setInterval('funca('+x+','+y+')',500);


You can use an anonymous function;

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

setInterval(function,milliseconds,param1,param2,...)

Update: 2018 - use the "spread" operator

_x000D_
_x000D_
function repeater(param1, param2, param3){_x000D_
   alert(param1);_x000D_
   alert(param2);_x000D_
   alert(param3); _x000D_
}_x000D_
_x000D_
let input = [1,2,3];_x000D_
setInterval(repeater,3000,...input);
_x000D_
_x000D_
_x000D_


That problem would be a nice demonstration for use of closures. The idea is that a function uses a variable of outer scope. Here is an example...

setInterval(makeClosure("Snowden"), 1000)

function makeClosure(name) {
var ret

ret = function(){
    console.log("Hello, " + name);
}

return ret;
}

Function "makeClosure" returns another function, which has access to outer scope variable "name". So, basically, you need pass in whatever variables to "makeClosure" function and use them in function assigned to "ret" variable. Affectingly, setInterval will execute function assigned to "ret".


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.


const designated = "1 jan 2021"

function countdown(designated_time){

    const currentTime = new Date();
    const future_time = new Date(designated_time);
    console.log(future_time - currentTime);
}

countdown(designated);

setInterval(countdown, 1000, designated);

There are so many ways you can do this, me personally things this is clean and sweet.


You can use an anonymous function;

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

now with ES5, bind method Function prototype :

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

Reference here


Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

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


Also, with IE Support > 9, you can pass more variables insider set interval that will be taken by you function. E.g:

function myFunc(arg1, arg2){};
setInterval(myFunc, 500, arg1, arg2);

Greetings!


I have had the same problem with Vue app. In my case this solution is only works if anonymous function has declared as arrow function, regarding declaration at mounted () life circle hook.


That problem would be a nice demonstration for use of closures. The idea is that a function uses a variable of outer scope. Here is an example...

setInterval(makeClosure("Snowden"), 1000)

function makeClosure(name) {
var ret

ret = function(){
    console.log("Hello, " + name);
}

return ret;
}

Function "makeClosure" returns another function, which has access to outer scope variable "name". So, basically, you need pass in whatever variables to "makeClosure" function and use them in function assigned to "ret" variable. Affectingly, setInterval will execute function assigned to "ret".


Also, with IE Support > 9, you can pass more variables insider set interval that will be taken by you function. E.g:

function myFunc(arg1, arg2){};
setInterval(myFunc, 500, arg1, arg2);

Greetings!


You can use a library called underscore js. It gives a nice wrapper on the bind method and is a much cleaner syntax as well. Letting you execute the function in the specified scope.

http://underscorejs.org/#bind

_.bind(function, scope, *arguments)


Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

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


This works setInterval("foo(bar)",int,lang);.... Jon Kleiser lead me to the answer.


I know this topic is so old but here is my solution about passing parameters in setInterval function.

Html:

var fiveMinutes = 60 * 2;
var display = document.querySelector('#timer');
startTimer(fiveMinutes, display);

JavaScript:

function startTimer(duration, display) {
    var timer = duration,
        minutes, seconds;

    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        --timer; // put boolean value for minus values.

    }, 1000);
}

Quoting the arguments should be enough:

OK --> reloadIntervalID = window.setInterval( "reloadSeries('"+param2Pass+"')" , 5000)

KO --> reloadIntervalID = window.setInterval( "reloadSeries( "+param2Pass+" )" , 5000)

Note the single quote ' for each argument.

Tested with IE8, Chrome and FireFox


Another solution consists in pass your function like that (if you've got dynamics vars) : setInterval('funca('+x+','+y+')',500);


By far the most practical answer is the one given by tvanfosson, all i can do is give you an updated version with ES6:

setInterval( ()=>{ funca(10,3); }, 500);

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.


Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

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


You can use an anonymous function;

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

This works setInterval("foo(bar)",int,lang);.... Jon Kleiser lead me to the answer.


You can use a library called underscore js. It gives a nice wrapper on the bind method and is a much cleaner syntax as well. Letting you execute the function in the specified scope.

http://underscorejs.org/#bind

_.bind(function, scope, *arguments)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to parameters

Stored procedure with default parameters AngularJS ui router passing data between states without URL C#: HttpClient with POST parameters HTTP Request in Swift with POST method In Swift how to call method with parameters on GCD main thread? How to pass parameters to maven build using pom.xml? Default Values to Stored Procedure in Oracle How do you run a .exe with parameters using vba's shell()? How to set table name in dynamic SQL query? How to pass parameters or arguments into a gradle task

Examples related to setinterval

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead? How can I pause setInterval() functions? Can clearInterval() be called inside setInterval()? Stop setInterval clearInterval() not working Calculating Page Load Time In JavaScript Javascript setInterval not working How to start and stop/pause setInterval? How do I reset the setInterval timer? jquery function setInterval