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); }
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With