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?
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?
Share Improve this question asked Mar 15, 2012 at 17:26 Itay GrudevItay Grudev 7,4344 gold badges57 silver badges93 bronze badges 1- Pointer to the same class ... – Itay Grudev Commented Mar 15, 2012 at 18:31
5 Answers
Reset to default 8Try 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.
If Animate
is a derived function from the prototype, you'll have to use:
setInterval(this.Animate.bind(this), this.speed);
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...
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.
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);
.