1
setInterval(this.Animate(), this.speed);

This is expected to be run every this.speed times. Yes, but the browsers run it only one time. What are the possible reasons for that?

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86

5 Answers5

8

Try to run your function without the parentheses, when you put parentheses it always calls the function instead of passing it, which is what you want here:

setInterval(this.Animate, this.speed);

If it still doesn't work, you should debug and find out what is the scope for 'this', as 'this' might change. You can do that by adding a breakpoint in your browser's JS debugger. Also, you can try this to avoid the scope problem with 'apply'

var animate = this.animate.apply(this)
setInterval(animate, this.speed);

p.s: It might be a good choice to avoid setInterval for animation as they might queue and then fire at once. Instead call setTimedout once and again at the end of the function (this.Animate) as so to create a loop.

Lior
  • 1,599
  • 17
  • 21
7

If Animate is a derived function from the prototype, you'll have to use:

setInterval(this.Animate.bind(this), this.speed);
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 2
    +1 Good possibility that the current `this` needs to be retained as the calling context. –  Mar 15 '12 at 17:31
5

Do the following:

setInterval(this.Animate, this.speed);

You are executing the function instead of assigning a reference to the function to be executed at a certain interval...

Alex
  • 34,899
  • 5
  • 77
  • 90
3

Let us look at your code

setInterval(this.Animate(), this.speed);

What it is saying is run the function this.Animate() right away and store what ever it returns to be called.

What you want to do is create a closure

var that = this;
setInterval( function(){ that.Animate() }, this.speed);

The that maintains the current scope.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

If you're looking for a JQuery refresh script, try:

refreshId = setInterval(function() {
    // Events or Actions
}, 5000);

If you ever want to Pause or Stop this, use clear interval: clearInterval(refreshId);.

Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57