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?
RobseAsked:
Who is Participating?
 
ZvonkoConnect With a Mentor Systems architectCommented:
The setTimeout statement is executed in global context and not in the Object context.
Therefore is this. not defined in global context (or it does reference to the function Object)
Perhps it helps to see the running version:
<script>

function test(){
     var tickCounter = 0;
     
     this.tick = function(gObjName)
     {                                        
                   
          tickCounter++;
         
          alert(tickCounter);
          setTimeout("self['"+gObjName+"'].tick('"+gObjName+"')", 1000);
     }    
}


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

</script>

0
 
RoonaanCommented:
Try using
setTimeout('tick', this, 1000);

-r-
0
 
0h4crying0utloudCommented:


You setTimeout function take string (name of a funcion), not a function object.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
thirdCommented:
try to add parenthesis to the function,

setTimeout(this.tick(), 1000);
0
 
ZvonkoSystems architectCommented:
Try in your browser before recommending infinite loops ;-)
0
 
thirdCommented:
yep. now i'm using task manager to end the process... ;-) my bad.
0
 
RobseAuthor Commented:
lol third yeah I tried that too :)

Thanks Zvonko for your explanation and good solution!

Robse
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.