5

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?

3 Answers 3

9

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);     
        };
    } 
Sign up to request clarification or add additional context in comments.

Comments

0

You could try this:

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

Comments

0

The reason your not able to use closures here is because setTimeout runs off the window object, so 'this' is always 'window'. You'll want to use a partial function application here to set the context (and optionally some predefined parameters!) of your function while keeping it as a reference, so it can be used as event handler! Neat eh? See below.

// 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);
  };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.