Search code examples
javascriptsettimeoutalertconfirm

Capturing confirm message triggered by setTimeout javascript


I'm making a board game and I have a function that calls various alerts based on the destination of the player. For the final destination, I am trying to call the alert message, then call a confirm message asking if they want to play again. I want to capture the confirm response and trigger a reset() function if they click OK.

For the order of the alert and then confirm, the only way I could think of to stagger them was to make the setTimeout delay a little bit longer for the confirm message than the alert message.

Also, my else statement is a console.log("Game over."), and this is showing up in the console even before the confirm message pops up that is supposed to trigger it. In addition, clicking OK or cancel on the confirm message is not triggering anything. Not sure what's going on.

function message(dest) {

if(dest===5) window.setTimeout(alert, 5000, "Great start.");
... (a lot more else if statements here)
else if (dest===134) {
    window.setTimeout(alert, 3000,"You made it.");
    if (window.setTimeout(confirm, 5000, "Game over. Do you want to play again?")==true) reset();
    else console.log("Game over.")
}

Solution

  • seems you are looking for something like this:

    http://jsfiddle.net/InferOn/Lrwur3ek/

    function message(dest) {
    
    if(dest===5) 
        window.setTimeout(alert, 5000, "Great start.");
    
    else if (dest===134) {
        window.setTimeout(alert, 3000,"You made it.");
        window.setTimeout(MyConfirm, 5000);
    
    
    }
    }
    
    function MyConfirm(){
        if(confirm("Game over. Do you want to play again?"))
            reset();
        else
            noReset();
    }
    
    function reset(){alert('reset');}
    function noReset(){alert('no reset');}
    
    message(134);
    

    btw I think setTimeout is not the right way to manage your events