WDI-SEA / game-project-issues

0 stars 0 forks source link

Trying to stop a setInterval inside of a function from the outside? #53

Closed jyang1003 closed 3 years ago

jyang1003 commented 3 years ago

What's the problem you're trying to solve?

I'm trying to stop the setInterval inside my function from the outside but may not be possible due to scope

Post any code you think might be relevant (one fenced block per file)

const level = (levelNumber) => {
    // every other lane switches direction for level 2
    //switch movement from += to -= for other direction 
    if (gameState < 3) {
        let spawnOne = setInterval(() => carSpawn(xPosition[levelNumber - 1][0], 0, carLane[0]), carSpawnTime())
        let spawnTwo = setInterval(() => carSpawn(xPosition[levelNumber - 1][1], 50, carLane[1]), carSpawnTime())
        let spawnThree = setInterval(() => carSpawn(xPosition[levelNumber - 1][2], 100, carLane[2]), carSpawnTime())
        let spawnFour = setInterval(() => carSpawn(xPosition[levelNumber - 1][3], 150, carLane[3]), carSpawnTime())
        let spawnFive = setInterval(() => carSpawn(xPosition[levelNumber - 1][4], 200, carLane[4]), carSpawnTime())
        let spawnSix = setInterval(() => carSpawn(xPosition[levelNumber - 1][5], 250, carLane[5]), carSpawnTime())
        let spawnSeven = setInterval(() => carSpawn(xPosition[levelNumber - 1][6], 300, carLane[6]), carSpawnTime())
        console.log('level function run')
    }
    return
}

const gameLoop = () => {
    // window.requestAnimationFrame(gameLoop);
    // clear the canvas
    ctx.clearRect(0, 0, game.width, game.height)
    player.render()
    player.movePlayer()
    if (gameState === 0) {
        gameState++
        level(gameState)
    }

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

no error message, but I need the level function from the first if check to stop running so that the second one in another if check can run smoothly

What is your best guess as to the source of the problem?

scope of the setInterval is local so it cannot be manipulated anywhere else

What things have you already tried to solve the problem?

Tried using clearInterval, tried refactoring the function so that it was a callback function for a setInterval outside, did not work