简体   繁体   中英

can't stop this recursive settimeout function in nodejs

I made this recursive set timeout function to send time for each game room but when the time finishes i cannot stop the function. i tried the clear timeout but it did not help so if anyone would help me.

setTimeout(function GameTime() {
    io.in(Rooms[picked].name).emit('PlayTime', timeleft);
    timeleft.x--; // HERE WHERE I DECREMENT THE TIME
    setTimeout(GameTime, 1000)
}, 1000)         

Assuming you're not stopping the loop, you has to stop it using the function clearTimeout .

A better approach for your scenario is using the function setInterval :

 var x = 3; var intervalId = setInterval(function GameTime() { //io.in(Rooms[picked].name).emit('PlayTime', timeleft); //timeleft.x--; // HERE WHERE I DECREMENT THE TIME x--; if (x < 0) { clearInterval(intervalId); console.log('finished!'); return; } console.log('looping!'); }, 1000) 

You need a reference to the setTimeout you want to clear:

 let timeoutId, gameTimeoutId timeoutId = setTimeout(function GameTime() { console.log('GameTime') gameTimeoutId = setTimeout(GameTime, 1000) }, 1000) setTimeout(function GameTime() { clearTimeout(timeoutId) clearTimeout(gameTimeoutId) }, 5000) 

This snippet will call GameTime each 1 second and after 5 seconds it removes the interval loop

As an alternative to this is to use setInterval, this will simplify you code considerable:

 const intervalId = setInterval(() => { console.log('GameTime') // do stuff }, 1000) setTimeout(() => { clearInterval(intervalId) }, 5000) 

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