2

I'm trying to wrap a setTimeout in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:

Here is the reference: enter link description here

For some reason it runs once and then stopped.

//Spaceship move
function spaceShipMove(spaceShipToMove){

    var randomY = Math.floor(Math.random());
    spaceShipToMove.style.webkitTransform = 'translate(-3000px, ' + randomY + 'px)';
}
  //Spaceship
    var spaceShipsList = createMultipleSpaceShips(500);
    for (var i = 0; i < spaceShipsList.length; i++){
        var aSpaceShip = spaceShipsList[i];
        app.dom.mainWrapper.appendChild(aSpaceShip);


        (function t() {
            setTimeout(function (spaceShipGo) {
                spaceShipMove(spaceShipGo);
            }, i * 300, aSpaceShip)
        })();
Edgar Kiljak
  • 1,160
  • 7
  • 27
  • [Minimal example](/help/mcve) please... – D. Pardal May 03 '18 at 08:22
  • Thank you. I have amended it. – Edgar Kiljak May 03 '18 at 08:28
  • 1
    do you really need to wrap your setTimeout inside an IIFE? I mean, the setTimeout will run without it – bobharley May 03 '18 at 08:31
  • I want this for infinite amount of time – Edgar Kiljak May 03 '18 at 08:39
  • You missed the point of using IIFE in the linked answer. Your named your function `t` but never use this name. Also, do you really need a separate timeout/interval? You almost certainly should have just one timeout scheduled at a time, and put the loop inside. That would spare you the whole problem of passing aSpaceShip there, which is not easily solvable. – Frax May 03 '18 at 09:20
  • If you want to call recursively your setTimeout, then you need to pass `t` in the setTimeout: just like in the linked answer. But you'll face an issue with your `i * 300` delay, I guess you'll want to delay their first occurence but keep them with the same 300ms delay. – Kaiido May 03 '18 at 09:21

1 Answers1

0

try this

for (var i = 0; i < spaceShipsList.length; i++){
 var aSpaceShip = spaceShipsList[i];
 app.dom.mainWrapper.appendChild(aSpaceShip);

 setTimeout(spaceShipMove.bind(null, aSpaceShip), i * 300)
}
LiH
  • 1
  • 1