+ 6
Need help with JS and setInterval...
Hello, I need help with a simple problem I presume... I want to create an rectangle, and move him from right to left with setInterval(). With my "move" function, it work, but when I want do this with my method update, the rectangle can't move, only drawing. Thanks. https://code.sololearn.com/W7k44CsWYDM7/?ref=app
4 Respuestas
+ 4
IdkWhoIAm AI *this in JS points to different objects based on it's execution context and whether you're in strict mode or not.
setInterval is a method of a Window object. You passed update to setInterval, then after some internal processing, Window will call the update method. In this case, *this points to Window not obstacles[0]. For the latter to happen, bind the update method when you pass it so *this always point to an obstacle.
obstacles[0].update.bind(obstacles[0])
Your English is fine. Glad to help.
+ 5
Remove the parentheses after update. You were invoking the function, not passing it to setInterval.
You might also need to bind update to obstacles[0] since the context has changed and this might not point to the expected object.
+ 5
Thank for your help.
I removed parenthesis after update, it's like the call to my function move : setInterval(move, 100); I think than I understood this.
But I dont understand "bind update to obstacles[0]", I need to add a line before setInterval ?
Sorry for my bad english...
+ 4
Ill read your explanation many times to understand a maximum.
I understand better now about error of my code, Ill search informations about "strict mode" too.
Thanks again for this fast and very good explanation.