views:

55

answers:

2

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>
+6  A: 

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

Nick Craver
+1 for the better explanation than my (now deleted) answer.
Yacoby
+5  A: 

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:

CMS
I see, thanks man. I gave the solution to Nick only because that worked very well for me. But I understand your point, and I definitely think that its a generally superior approach. Plus I didn't realize that set interval could take a function like that. +1
CJ