简体   繁体   中英

Immediately invoked function expression for setTimeout doesn't work

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)
        })();

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM