CJ.
CJ.

Reputation: 153

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? Also, I'm using Jquery.

<script>
$(function(){
   var kP = new Kompost();
   setInterval('kP.play()', kP.interval);
});

var Kompost = function()
{
   this.interval = 5000;
   var kompost = this;

   this.play = function()
   {
      alert("hello");
   }
}
</script>

Upvotes: 2

Views: 3000

Answers (3)

Bhuwan Prasad Upadhyay
Bhuwan Prasad Upadhyay

Reputation: 3056

It works on every where like thymeleaf etc...

function load() {
  alert("Hello World!");
}
setInterval(function () {load();}, 10000);

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827286

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 = new Kompost();
 setInterval(function () {
   kP.play();
 }, kP.interval);
});

See also:

Upvotes: 8

Nick Craver
Nick Craver

Reputation: 630379

Call it like this:

$(function(){
   var kP = new Kompost();
   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:

var Kompost = function()
{
   this.interval = 5000;
   var kompost = this;
   this.play = function() {
     alert("hello");
   };
};

$(function(){
   var kP = new Kompost();
   setInterval(kP.play, kP.interval);
});

You can see it working here

Upvotes: 7

Related Questions