Javascript Setinterval Not Working For Object
SO, I'm trying to create a javascript object, and use the setInterval method. This doesn't seem to be working. If I remove the quotes, then the method runs once. Any ideas why? Als
Solution 1:
The solution provided by @Yacoby and @Nick, will work only if the play
method doesn't use the this
value inside itself, because the this
value will point to the global object.
To handle this you need another approach, for example:
$(function(){
var kP = newKompost();
setInterval(function () {
kP.play();
}, kP.interval);
});
See also:
Solution 2:
Call it like this:
$(function(){
var kP = newKompost();
setInterval(kP.play, kP.interval);
});
The problem is that kP
is inside that document.ready
handler and not available in the global context (it's only available inside that closure). When you pass a string to setInterval()
or setTimeout()
it's executed in a global context.
If you check your console, you'll see it erroring, saying kP
is undefined, which in that context, is correct. Overall it should look like this:
varKompost = function()
{
this.interval = 5000;
var kompost = this;
this.play = function() {
alert("hello");
};
};
$(function(){
var kP = newKompost();
setInterval(kP.play, kP.interval);
});
Solution 3:
It works on every where like thymeleaf etc...
function load() {
alert("Hello World!");
}
setInterval(function () {load();}, 10000);
Post a Comment for "Javascript Setinterval Not Working For Object"