Search code examples
javascriptjquerypause

Javascript pause - disable a function until another one finishes


I have two functions, first one selects stuff and the other evaluates it with a delay, like this:

function select() {
    // selecting stuff
    window.setTimeout(evaluate, 1000);
}
function evaluate() {
    // evaluating stuff
}

The issue is, the selecting function should be disabled until the second is done. I know it's impossible to completely pause Javascript, but the first function firing while the other one is waiting or working seriously messes everything up. I already tried moving code around to other functions and delaying those, but nothing works.

Thanks in advance!


Solution

  • Who said it's impossible? You can check if the timer is currently running by saving and tracking its ID:

    var timeout = null;
    function select() {
        if( timeout ) { // check if the timer ID is set
            return;
        }
        // selecting stuff
        timeout = window.setTimeout(evaluate, 1000); // return the ID of the timer
    }
    function evaluate() {
        // evaluating stuff
        window.clearTimeout(timeout); // clear the timer ID
        timeout = null; // reset the timer ID
    }