I recently started learning javascript to help maintain some stuff and ran into this issue today:
this.moveChar = function(){
// body here
setTimeout(moveChar,1000);
}
this.initialise= function(){
this.moveChar();
}
When initialise is called, I expected moveChar to be called, then repeated call itself once every 1000ms
However, what actually happens is moveChar gets called once then that's it. Based on other stackoverflow posts I read, I suspected it might be something to do with the function being expressed rather than declared. I have tried to use
this.moveChar = function recMove(){
// body here
setTimeout(recMove,1000);
}
without luck either.
Any suggestions on how I can fix this?
EDIT: Main thing I need to do is have the moveChar function called once every second. If there is a better approach than setTimeout recursion, I'm open to it
thisin sidebody here? If so, you should bind correct context while call.setInterval. Second, when you dosetTimeout(moveChar,1000);, JS will look for a variable with namemoveCharand will not find anything.moveCharis a part of an object and has to be accessed asobject.moveCharin your casethis.moveChar. Now since you are looping recursively, you will have to bindthisagain. so your code becomessetTimeout(this.moveChar.bind(this), 1000)setIntervalis completely other feature. with tailsetTimeoutyou'll never get two calls at same time.