Q:

How to properly use setTimeout with immediately invoked function?

I'm making a game where if the player hits the enemy from top, after 1 sec period,(that is to show dying animation), the enemy will splice out of the array.
It works fine while killing each enemy one by one, but when two enemies get killed at the same time, a problem occurs.
For example, if the enemies were in position 2 and 3 of the array when killed. After splicing it, the position 3 comes to position 2.
The second splice doesn't work as the position is already changed.
Is there a fix to this or a different method, or is my logic just plain invalid.
   for (var i = 0; i < enemies.length; i++) {
     var collWithPlayer= that.collisionCheck(enemies[i], player);

         if (collWithPlayer == 't') { //kill enemies if collision is from top
          enemies[i].state = 'dead';
          player.velY = -((player.speed));

          score.totalScore += 1000;
          score.updateTotalScore();

          //immediately-invoked function for retaining which enemy died
          (function(i){
            setTimeout(function() { //show squashed enemy for a brief moment then splice
              enemies.splice(i, 1);
            }, 1000);
          })(i);

A:

So what I did was use a filter function on the enemy array that returns a new array containing only enemies that are still alive, or have only been dead for a little while.
Creating a delay between 'dead' and 'remove' can be done with a 'decay' property on an object. You can update/increase the value of this decay-property on every game-tick.

// inside a gametick loop

var enemyCollisions = [];

enemies = enemies.filter(function (item) {
  collisionWithPlayer = that.collisionCheck(item, player);
  
  if (collisionWithPlayer === 't') {
    item.state = 'dead';
    item.decay = 0;
    
    enemyCollisions.push({
      direction: collisionWithPlayer,
      with: item
    });
  }
  
  if (typeof item.decay === 'number') {
    item.decay = item.decay + 1;
  }
  
  return (item.state !== 'dead' && item.decay > 62);
});


enemyCollisions.forEach(function (item) {
  if (item.direction === 't') {
    player.velY = -((player.speed));

    score.totalScore += 1000;
    score.updateTotalScore();
  } else {
    //TODO deal with collisions other then 't'
  }
});

