Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class prototype method by a setInterval event

Tags:

javascript

I have a simple javascript class.

One method of this class sets up a timer using setInterval function. The method that I want to call every time the event fires is defined inside the same class.

The question is, how can I pass this method as a parameter to the setInterval function?

One attempt was setInterval('this.showLoading(), 100). But doesn't work. This method access class properties, so I need the 'this' reference.

This is the sample code:

    function LoadingPicture(Id)     {         this.imgArray = null;         this.currentImg = 0;         this.elementId = Id;         this.loadingTimer = null;     }      LoadingPicture.prototype.showLoading = function()     {         if(this.currentImg == imgArray.length)             currentImg = 0;          document.getElementById(this.elementId).src = imgArray[this.currentImg++].src;     }       LoadingPicture.prototype.StartLoading = function()     {         document.getElementById(this.elementId).style.visibility = "visible";         loadingTimer = setInterval("showLoading()", 100);     } 
like image 677
Andres Avatar asked Jan 04 '10 20:01

Andres


People also ask

How do you call a setInterval function?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.

How do you pass parameters to setInterval?

The setInterval() method can pass additional parameters to the function, as shown in the example below. setInterval(function, milliseconds, parameter1, parameter2, parameter3); The ID value returned by setInterval() is used as the parameter for the clearInterval() method.


1 Answers

setInterval can take a function directly, not just a string. https://developer.mozilla.org/en/DOM/window.setInterval

i.e.

loadingTimer = setInterval(showLoading, 100); 

But, for optimal browser compatibility, you should use a closure with an explicit reference:

 var t = this;  loadingTimer = setInterval(function(){t.showLoading();}, 100); 
like image 76
Lilith River Avatar answered Oct 14 '22 20:10

Lilith River