Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.
function Foo() {} Foo.prototype = { bar: function () { this.baz(); }, baz: function () { this.draw(); requestAnimFrame(this.baz); } };
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Yes, setInterval repeats until you call clearInterval with the interval to stop.
setTimeout(function, milliseconds ) Executes a function, after waiting a specified number of milliseconds. setInterval(function, milliseconds ) Same as setTimeout(), but repeats the execution of the function continuously.
“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.
Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either
This way, accessing the baz
property and calling it happen at the same time, which is necessary for the this
to be set correctly inside the method call.
You will need to save the this
from the outer function in a helper variable, since the inner function will refer to a different this
object.
var that = this; setInterval(function(){ return that.baz(); }, 1000);
In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
Fat arrow anonymous functions preserve the this
from the surrounding function so there is no need to use the var that = this
trick. To see if you can use this feature, consult a compatibility table like this one.
A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.
setInterval( this.baz.bind(this), 1000 ); //dojo toolkit example: setInterval( dojo.hitch(this, 'baz'), 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