简体   繁体   中英

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!

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
}

I would think this problem should be using callbacks. A callback is a function to be executed after another function is executed. This way you guarantee the function is ran after your other has ran. Also, how are you getting data? Many of the SQL functions have built in callback, ie success, functions that you can use to call your other function. You could end up in callback hell, but you use the other functions callback to continue processing your data.

Excellent article here:

http://dreamerslab.com/blog/en/javascript-callbacks/

The correct way to handle this kind of situation is using promises. I prefer using the Q library ( https://github.com/kriskowal/q ), but ofcourse you could use jquery too. Lets say you want to run select, the run evaluate and make select disabled until evaluate is done:

 var deferred = jQuery.Deferred();

 function select() {
     if (deferred.state() === "pending") {
      console.log("Evaluate not finished");
    } else {
       // select stuff
        evaluate(deferred.promise());
    }
}

function evaluate(promise) {
    // evaluating stuff
    promise.resolve();
}

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