Please tell 500мс how to make the function run every time with a delay of 500мс (frameWidth / 2) != enemyDistance , after the function is closed.

 var motionEnemy = function () { if (rightSid === true) { while ( (frameWidth / 2) != enemyDistance ) { console.log('step'); enemy.css({marginRight: enemyDistance + 'px'}); enemyDistance += STEP_LENGHT; setTimeout(motionEnemy,__self.GAME_TICK*); } }; setTimeout(motionEnemy(),__self.GAME_TICK); 
  • 2
    while replace with if ? - Maxim Timakov

1 answer 1

As @Max Timakov correctly wrote, while in this case is not necessary, because there is a recursion variable motionEnemy, contains a function that, when the condition is met, calls the variable again, so if enough to check the condition in every call to variable.

UPD Corrected the narrative and moved i++; higher by the request of viewers.

 var i = 0; var j = 10; var motionEnemy = function() { if (j >= i) { console.log('step' + i); i++; setTimeout(motionEnemy, '500'); } }; setTimeout(motionEnemy, '1500'); 

  • 3
    there is no recursion here — motionEnemy() does not call itself (neither directly nor indirectly: i++ is executed before the next call), but delegates the javascript call to the engine (stackoverflow will not work). - jfs
  • and if I write the function motionEnemy() {} instead of var motionEnemy = function() {} , will this be a recursion? - MasterAlex
  • one
    No, it doesn’t change, how setTimeout() works. - jfs
  • @jfs, hmm, strangely, on Habré and here I met examples where exactly such a call through setTimeout() is called indirect recursion, corrected the answer, so right? - MasterAlex
  • one
    not. Even, function f() { setTimeout(f, 0); } function f() { setTimeout(f, 0); } not a recursion. Recursion: function f() { f(); } function f() { f(); } . Present instead of setTimeout() written (not a real implementation): queue.push({function: motionEnemy, args: [], deadline: current_time + 500}) and after control passes to the engine: it calls the appropriate functions from queues of queue whose deadline passed. Look at the pictures - jfs