Javascript setInterval runs only one time

徘徊边缘 提交于 2020-01-14 03:48:05

问题


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?


回答1:


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

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



回答2:


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.




回答3:


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...




回答4:


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.




回答5:


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);.



来源:https://stackoverflow.com/questions/9724968/javascript-setinterval-runs-only-one-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!