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

Community
  • 1
  • 1
Squirrl
  • 4,909
  • 9
  • 47
  • 85

2 Answers2

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);
PSL
  • 123,204
  • 21
  • 253
  • 243
  • THanks. Perfect but Cherniv beat u by 9 secs – Squirrl Jun 27 '13 at 05:24
  • 1
    @Squirrel Np. You are welcome Just added explanation for making it more clear, which probably is more important that the answer itself.. :) – PSL Jun 27 '13 at 05:25
  • 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 – Squirrl Jun 27 '13 at 05:45
  • 1
    @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.. – PSL Jun 27 '13 at 05:49
5

Use closure:

setInterval( function(){ magicWords(7,3); }, 1000); 
Community
  • 1
  • 1
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146