Link to home
Start Free TrialLog in
Avatar of Robse
Robse

asked on

setTimeout in class function

Why is the timeout only executed once?

function test()
{
      var tickCounter = 0;
      
      this.tick = function()
      {                                                
                        
            tickCounter++;
            
            alert(tickCounter);
            
            setTimeout(this.tick, 1000);
      }      
}

in index.htm:

var t = new test();
t.tick()

navigator says "useless Timeout" and IEX says "invalid argument"
So what do I need to do to fix it?
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Try using
setTimeout('tick', this, 1000);

-r-
Avatar of 0h4crying0utloud
0h4crying0utloud



You setTimeout function take string (name of a funcion), not a function object.
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
try to add parenthesis to the function,

setTimeout(this.tick(), 1000);
Try in your browser before recommending infinite loops ;-)
yep. now i'm using task manager to end the process... ;-) my bad.
Avatar of Robse

ASKER

lol third yeah I tried that too :)

Thanks Zvonko for your explanation and good solution!

Robse