How to call this function in setTimeout in JS?

I have the following JS:

function TrackTime() {

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

}

I tried this with closure (see above), as well as about a dozen other ways. I can't seem to get this to work in any browser. The setTimeout function works great when not called in a class function. Can someone please help me with this?

+5
source share
3 answers

This is due to a change in the scope of "this" when the function is executed.

Try this - this trick ..

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

            setTimeout(function(){that.CountBack(secs)}, SetTimeOutPeriod);     
        };
    } 
+9
source

You can try the following:

var that = this;
this.CountBack = function (secs) {
    setTimeout(function () {that.CountBack(secs)}, SetTimeOutPeriod);
}
0
source

, , , setTimeout window, 'this' "". , (, , !) , , ! , ? . .

// This will call a function using a reference with predefined arguments.
function partial(func, context /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments, 2);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(context ? context : this, allArguments);
  };
}
0
source

All Articles