373

Please advise how to pass parameters into a function called using setInterval.

My example setInterval(funca(10,3), 500); is incorrect.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rakesh
  • 5,793
  • 8
  • 36
  • 37

19 Answers19

626

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

setInterval( function() { funca(10,3); }, 500 );
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 4
    what should be for dynamic parameter? – rony36 Aug 22 '13 at 17:16
  • 32
    @rony36 - you probably want to have a function that creates the interval timer for you. Pass in the parameter to the function so its value is captured in the function closure and retained for when the timer expires. `function createInterval(f,dynamicParameter,interval) { setInterval(function() { f(dynamicParameter); }, interval); }` Then call it as `createInterval(funca,dynamicValue,500);` Obviously you can extend this for more than one parameter. And, please, use more descriptive variable names. :) – tvanfosson Aug 22 '13 at 18:12
  • @tvanfosson: awesome answer! Do you know how to clear the interval form *within* function `funca`? – Adam Nov 02 '16 at 22:35
  • @tvanfosson Thanks. My bad, but I actually meant the createInterval example you gave in the comment section. How would it work for that? I was thinking of passing a timer variable as a dynamic parameter too, but not sure how or if that makes sense. In the interest of clarity I added a new question here: http://stackoverflow.com/questions/40414792/disable-timer-within-setinterval-function-with-dynamic-parameters – Adam Nov 04 '16 at 03:26
  • This worked for me but why is this the case? – Paula Livingstone Nov 05 '21 at 08:21
110

Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

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

Kev
  • 15,899
  • 15
  • 79
  • 112
91

now with ES5, bind method Function prototype :

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

Reference here

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
sbr
  • 4,735
  • 5
  • 43
  • 49
  • 3
    This is the best answer, however it might have unexpected behaviour depending on the function. e.g. ``console.log.bind(null)("Log me")`` will throw ``Illegal invocation``, but ``console.log.bind(console)("Log me")`` will work as expected. This is because ``console.log`` requires ``console`` as the ``this`` arg. – Indy Feb 16 '14 at 07:53
  • 1
    By far the best answer. Lean and clean. Thanks a lot! – Tobi Sep 02 '14 at 10:01
  • Very clean and efficient! – contactmatt Dec 02 '14 at 18:55
  • 2
    Just add that works with Chrome>=7, Firefox>=4.0, Explorer>=9, Opera>=11.60, Safari>=5.1 (Source: https://developer.mozilla.org/ca/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – Roger Veciana Jun 15 '16 at 11:41
  • The MDN link provided by @RogerVeciana is broken now, so here's the updated one - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – yoniLavi Mar 19 '21 at 12:14
39
     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
manas
  • 6,119
  • 10
  • 45
  • 56
33

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.

Juan
  • 421
  • 5
  • 5
  • 1
    You can access by Classname.prototype.someFunction.parameter1 – JoaquinG Oct 15 '12 at 10:07
  • 3
    Adding parameters to an object or function can cause the compiler to slow down since it will have to rebuild it's native code representation of the object (for instance if this was done in a hot loop) so be careful. – mattdlockyer Feb 20 '14 at 18:50
23
setInterval(function,milliseconds,param1,param2,...)

Update: 2018 - use the "spread" operator

function repeater(param1, param2, param3){
   alert(param1);
   alert(param2);
   alert(param3); 
}

let input = [1,2,3];
setInterval(repeater,3000,...input);
swogger
  • 1,079
  • 14
  • 30
19

You can use an anonymous function;

setInterval(function() { funca(10,3); },500);
Simon
  • 37,815
  • 2
  • 34
  • 27
14

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);
A.rodriguez
  • 270
  • 1
  • 4
  • 11
  • 1
    Are you saying that ()=>{} is ES6's new way to replace function(){}? Interesting. First, I thought rockets were passe. And, unless this syntax has other common uses, it's just very, very odd. I see they are "fat arrows". Still, odd. I guess someone likes it and it's a matter of opinion. – Richard_G Nov 20 '16 at 20:20
7

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

animuson
  • 53,861
  • 28
  • 137
  • 147
waterazu
  • 79
  • 1
  • 3
6

The best solution to this answer is the next block of code:

setInterval(() => yourFunction(param1, param2), 1000);
Peter Palmer
  • 726
  • 11
  • 18
4
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.

Allaye
  • 833
  • 6
  • 18
1

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);
}
Kaan Karaca
  • 190
  • 3
  • 12
  • i need to access a value once when calling the function, but not each second, so your answer provides this, (eg `timer`), but how do you `clearInterval()` in this scenario? – user1063287 Sep 29 '18 at 08:55
1

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!

Samuel Diez
  • 541
  • 4
  • 5
1

This worked for me

let theNumber = document.getElementById('number');
let counter = 0;

function skills (counterInput, timer, element) {
  setInterval(() => {
    if(counterInput > counter) {
      counter += 1;
      element.textContent = `${counter} %` 
    }else {
      clearInterval();
    }
  }, timer)
}

skills(70, 200, theNumber);
0

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

nonozor
  • 865
  • 2
  • 14
  • 24
0

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)

Sagar Parikh
  • 306
  • 3
  • 7
0

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".

Aleksey Kanaev
  • 293
  • 7
  • 13
0

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.

Srdjan Milic
  • 328
  • 2
  • 14
0

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

bipen
  • 36,319
  • 9
  • 49
  • 62
Stephen
  • 17
  • 1