Keith Rousseau
Keith Rousseau

Reputation: 4475

window.setInterval from inside an object

I'm currently having an issue where I have a javascript object that is trying to use setInterval to call a private function inside of itself. However, it can't find the object when I try to call it. I have a feeling that it's because window.setInterval is trying to call into the object from outside but doesn't have a reference to the object. FWIW - I can't get it to work with the function being public either.

The basic requirement is that I may need to have multiple instances of this object to track multiple uploads that are occurring at once. If you have a better design than the current one or can get the current one working then I'm all ears.

The following code is meant to continuously ping a web service to get the status of my file upload:

var FileUploader = function(uploadKey) {
    var intervalId;

    var UpdateProgress = function() {
        $.get('someWebService', {},
        function(json) {
            alert('success');
        });
    };

    return {
        BeginTrackProgress: function() {
            intervalId = window.setInterval('UpdateProgress()', 1500);
        },

        EndTrackProgress: function() {
            clearInterval(intervalId);
        }
    };
};

This is how it is being called:

var fileUploader = new FileUploader('myFileKey');
fileUploader.BeginTrackProgress();

Upvotes: 0

Views: 4801

Answers (3)

Justin
Justin

Reputation: 4624

+1 to Andy E's head (I can't upvote yet, doh!)

Another gotcha that could get you is if you use this from within the called function.

Then doing exactly what Andy has with this addition should get you by.

var that = this;
window.setInterval(function() {
    function1.apply(that);
    function2.apply(that);
}, 1500);

Upvotes: 0

Andy E
Andy E

Reputation: 344547

Because it is an eval expression, it does not have access to the scope that setInterval is created in. Try:

intervalId = window.setInterval(UpdateProgress, 1500)

It is generally good practice to avoid eval style expressions wherever possible. For instance, if you wanted to call several functions from the same timer, you would use an anonymous function instead of a string.

window.setInterval(function () {
    function1();
    function2();
}, 1500)

See also

Upvotes: 2

Sean Kinsey
Sean Kinsey

Reputation: 38046

Use this

 intervalId = window.setInterval(UpdateProgress, 1500);

setInterval with a literal argument will eval this in the global scope where UpdateProgress is not accessible.

Upvotes: 8

Related Questions