2

My function runs correctly once but I want it to run repeatedly:

$('button').click( function(){

    setInterval(magicWords(7,3), 1000); 

});

I tried hardwiring the parameters in the function itself and running it parameter-less, but still its a no go...?

1
  • 1
    You could also use setInterval(magicWords.bind(this, 7, 3), 1000); Commented Jun 27, 2013 at 5:27

2 Answers 2

8

You can do this way.

$('button').click( function(){

    setInterval(function(){
        magicWords(7,3)
     }, 1000); 

});

When you do setInterval(magicWords(7,3), 1000); it invokes the function as it executes the statement and effectively the result of your function (probably undefined if it does not return anything) will be set to run at that interval not the function itself. ou can use

And of-course if you are ready to add a shim for support for earlier browsers you can use ecmaScript 5 function.bind. This will bind y our function with specified context and parameters whenever invoked.

setInterval(magicWords.bind(this, 7,3), 1000);
Sign up to request clarification or add additional context in comments.

4 Comments

THanks. Perfect but Cherniv beat u by 9 secs
@Squirrel Np. You are welcome Just added explanation for making it more clear, which probably is more important that the answer itself.. :)
U do have a better answer but Cherniv was first and u do have way more points than him, and I'm a bleeding heart communist. Thanks again tho
@Squirrel haha lol no issues. I just wanted to make my answer more clear explaining what happened actually and any other options available, also i believe in adding details as much as possible so that the solution makes sense..
5

Use closure:

setInterval( function(){ magicWords(7,3); }, 1000); 

2 Comments

Thanks works perfect. U gotta wait 12 min for the green checkmark
@Squirrel great! it is exactly time for you to read about closures :D

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.