Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call this.function within setTimeout in JS?

Tags:

javascript

I have the following JS:

function TrackTime() {

    this.CountBack = function(secs) {
        setTimeout(function(){this.CountBack(secs)}, SetTimeOutPeriod);
    }

}

I have tried this with a closure (seen above) and also about a dozen other ways. I can't seem to get this to work in any browser. The setTimeout function works fine when not being called in a "class" function. Can someone please help me with this?

like image 923
Josh Avatar asked May 03 '11 20:05

Josh


1 Answers

This happens because of the change in the scope of "this" when the function is executed.

Try that-this trick..

    function TrackTime() {  
        this.CountBack = function(secs) {         
            var that = this;

            setTimeout(function(){that.CountBack(secs)}, SetTimeOutPeriod);     
        };
    } 
like image 150
Chandu Avatar answered Oct 16 '22 21:10

Chandu