Question

I created a little Game and that should create every 1sec a enemy till there are 10 enemy (10sec) if i do it without clearInterval it creates the whole time enemys so i want to stop when it reach 10

var initEnemy = function ()
{
    //enemy div
    for(var i = 0; i < 10; i++)
    var timerid = null;
    function IntervalFunction()
    {
        var randomX = Math.floor(Math.random() * 190);
        var randomY = Math.floor(Math.random() * 50);
        enemy.push(new Enemy(randomX, randomY).create());
    }
    IntervalFunction();
    setInterval(IntervalFunction,1000);
    clearInterval(IntervalFunction),10000);
}
Was it helpful?

Solution

clearInterval doesn't take second argument.

And setTimeout is easier to wrap head around... A simple approach is to count how many enemies you've created so far and not run setTimeout when the limit is reached:

var initEnemies = function () {

    var numEnemiesCreated = 0;

    function createAnotherEnemy() {
        var randomX = Math.floor(Math.random() * 190);
        var randomY = Math.floor(Math.random() * 50);
        enemy.push(new Enemy(randomX, randomY).create());

        numEnemiesCreated += 1;
        if (numEnemiesCreated < 10)
            setTimeout(createAnotherEnemy, 1000);

    }

    createAnotherEnemy();
}

And a version with for loop, it schedules function calls 0s, 1s, 2s, ... , 9s from now:

var initEnemies = function () {

    function createEnemy() {
        var randomX = Math.floor(Math.random() * 190);
        var randomY = Math.floor(Math.random() * 50);
        enemy.push(new Enemy(randomX, randomY).create());
    }


    for (var i=0; i < 10; i++)
        setTimeout(createEnemy, i * 1000);
}

update

Here's a version with setInterval and clearInterval. You still have to count how many enemies you've created so far, and you have to use interval id in clearInterval call. Haven't tested this, sorry!

var initEnemies = function () {
    var numEnemiesCreated = 0;
    var intervalId;

    function createEnemy() {
        var randomX = Math.floor(Math.random() * 190);
        var randomY = Math.floor(Math.random() * 50);
        enemy.push(new Enemy(randomX, randomY).create());

        // Unschedule ourselves after 10th run
        numEnemiesCreated += 1;
        if (numEnemiesCreated == 10)
            clearInterval(intervalId);    
    }


    intervalId = setInterval(createEnemy, 1000);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top