Search code examples
javascriptjquerydelaypause

jquery pause before displaying next step


On button next click (Game context), I want to make pause to show correct answer before showing next question. how can I do it? I try this :

showCorrectAnswer();
questionCounter++;
setTimeout(displayNext(), 6000);
/* Or */
showCorrectAnswer();
questionCounter++;
wait(6000);
displayNext();

/*with wait*/
function wait(ms){
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
        end = new Date().getTime();
    }
}

But does not work. Thanks


Solution

  • You are supposed to pass either an anonymous function to setTimeout() (in which you place what you want to execute when the timeout expires) or the name of a defined function. If you place () after the name, as you did, the function is executed when the setTimeout() is parsed, not when it expires, expecting the result of running your function to return another function that will be executed when the setTimeout() expires - much like the anonymous function does.

    Either of the following will work as expected. Name of function:

    showCorrectAnswer();
    questionCounter++;
    setTimeout(displayNext, 6000);
    

    ...or anonymous wrapper:

    showCorrectAnswer();
    questionCounter++;
    setTimeout(function(){
      displayNext();
    }, 6000);
    

    In most real life scenarios, it is advisable to change questionCounter value inside the displaynNext() function, not before.