Pass parameters in setInterval function

Viewed 282181

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

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

19 Answers

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

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

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);
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.

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

setInterval(() => yourFunction(param1, param2), 1000);

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

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.

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!

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);
Related