+ 1
Why does my animation not work? I tried a lot of things with setInterval and setTimeout on different position. Can anyone help?
7 Respuestas
+ 1
When update is invoked, *this will point to the Window object, not sprite. If you were expecting the latter, use binding at line 39:
setInterval(update, 1000)
The reason is *this in JS behaves a little different from other languages. I explained it in this question here:
https://www.sololearn.com/Discuss/1530902/need-help-with-js-and-setinterval
About convention, declare the methods inside the constructor function instead of assigning global functions, or just use ES6 classes. I refactored some lines of your code here:
https://code.sololearn.com/WkycQ3MlE1vf/#js
+ 1
Thanks for your assistance! Now it works and I will try to add some more sprites and collision detection.
However this line looks a Little bit strange for me:
setInterval(this.update.bind(this), 100);
I hope this will become more clear when I read your further explaination.
+ 1
Why it works here without binding?
https://code.sololearn.com/WCSjkN7QAegE/?ref=app
+ 1
*this refers to the current object, in this case *s. If you're calling it from the outer scope, it looks like
setInterval(s.update.bind(s), 100);
Which won't any different from
setInterval(this.update.bind(this), 100);
Ayhas code used an anonymous function, which formed a closure. It's a bit difficult to briefly explain closures though. They capture the environment (or retain references to their scope) in which they were declared.
To put it simply, *this always refer to the inner function so binding is needed. Ayhas's function passed to setInterval has no *this.
+ 1
Mirko Klotzsche clearInterval is definitely suitable here. What makes it "seem" like not working?
0
How can I stop that animation? It seems that clearInterval(interval) is not working.
0
Well it does not stop.