17

How do I pass arguments in the setInterval function Eg:

 intId = setInterval(waiting(argument), 10000);

It shows error : useless setInterval call (missing quotes around argument?)

2
  • 1
    setInterval(function(){waiting(argument)}, 10000) Commented Mar 14, 2013 at 13:19
  • possible duplicate of Pass parameters in setInterval function Commented Apr 8, 2014 at 21:29

5 Answers 5

47

Use an anonymous function

 intId = setInterval(function(){waiting(argument)}, 10000);

This creates a parameterless anonymous function which calls waiting() with arguments

Or use the optional parameters of the setInterval() function:

 intId = setInterval(waiting, 10000, argument [,...more arguments]);

Your code ( intId = setInterval(waiting(argument), 10000);) calls waiting() with argument, takes the return value, tries to treat it as a function, and sets the interval for that return value. Unless waiting() is a function which returns another function, this will fail, as you can only treat functions as functions. Numbers/strings/objects can't be typecast to a function.

Sign up to request clarification or add additional context in comments.

Comments

10

You can use Function#bind:

intId = setInterval(waiting.bind(window, argument), 10000);

It returns a function that will call the target function with the given context (window) and any optional arguments.

Comments

7

Use this method:

 var interval = setInterval( callback , 500 , arg1 , arg2[, argn ] );
 [...]
 function callback(arg1, arg2[, etc]){
 }

More info here: window.setInterval

Comments

1

You can use the bind and apply functions to store the argument in state.

Example using bind in node shell:

> var f = function(arg) { console.log (arg);}
> f()
undefined
> f("yo")
yo
> var newarg = "stuff";
> f(newarg)
stuff
> var fn = f.bind(this, newarg);
> fn()
stuff
> var temp = setTimeout(fn,1000)
> stuff

Comments

-3

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

1 Comment

This is the question you were trying to answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.