Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Breaking out of setTimeout loop

Breaking out of setTimeout loop

Problem

I'm having some trouble breaking out of a Settimeout Loop.

    for (var i = 0; i 

I've read like 100 Settimeout related posts, but can't figure this one out.

edit:

Let me clarify a bit when I'm trying to accomplish.

My game has 75 turns, each Turn should take about 500ms, during that turn I want to check if a condition is met and announce that the player won, after the player has won there is no need to continue the rest of the turns.

Problem courtesy of: Martijn

Solution

Instead of setting all those timers, create one continuous timer with setInterval:

var counter = 0;

var timer = setInterval(function () {

    console.log("turn no. " + counter);

    if (table.game.playerWon) {
        console.log('Player won');
    }

    if (counter >= 75 || table.game.playerWon) {
        clearInterval(timer);
    }

    counter++;

}, 100);

If your turns should take 500ms, change that last 100 to 500.

Solution courtesy of: Joseph Silber

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Breaking out of setTimeout loop

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×