+ 1

Why does my animation not work? I tried a lot of things with setInterval and setTimeout on different position. Can anyone help?

https://code.sololearn.com/WiZsVI5LjpIm/?ref=app

10th Oct 2018, 11:46 AM
Mirko Klotzsche
Mirko Klotzsche - avatar
7 Antworten
+ 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
10th Oct 2018, 2:34 PM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 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.
10th Oct 2018, 4:04 PM
Mirko Klotzsche
Mirko Klotzsche - avatar
+ 1
Why it works here without binding? https://code.sololearn.com/WCSjkN7QAegE/?ref=app
10th Oct 2018, 4:51 PM
Mirko Klotzsche
Mirko Klotzsche - avatar
+ 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.
11th Oct 2018, 12:45 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 1
Mirko Klotzsche clearInterval is definitely suitable here. What makes it "seem" like not working?
12th Oct 2018, 12:16 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
0
How can I stop that animation? It seems that clearInterval(interval) is not working.
11th Oct 2018, 11:16 PM
Mirko Klotzsche
Mirko Klotzsche - avatar
0
Well it does not stop.
12th Oct 2018, 12:21 AM
Mirko Klotzsche
Mirko Klotzsche - avatar