Wait until a condition is true?

前端 未结 7 1939
日久生厌
日久生厌 2020-12-09 08:32

I\'m using navigator.geolocation.watchPosition in JavaScript, and I want a way to deal with the possibility that the user might submit a form relying on locatio

7条回答
  •  一向
    一向 (楼主)
    2020-12-09 09:11

    Personally, I use a waitfor() function which encapsulates a setTimeout():

    //**********************************************************************
    // function waitfor - Wait until a condition is met
    //        
    // Needed parameters:
    //    test: function that returns a value
    //    expectedValue: the value of the test function we are waiting for
    //    msec: delay between the calls to test
    //    callback: function to execute when the condition is met
    // Parameters for debugging:
    //    count: used to count the loops
    //    source: a string to specify an ID, a message, etc
    //**********************************************************************
    function waitfor(test, expectedValue, msec, count, source, callback) {
        // Check if condition met. If not, re-check later (msec).
        while (test() !== expectedValue) {
            count++;
            setTimeout(function() {
                waitfor(test, expectedValue, msec, count, source, callback);
            }, msec);
            return;
        }
        // Condition finally met. callback() can be executed.
        console.log(source + ': ' + test() + ', expected: ' + expectedValue + ', ' + count + ' loops.');
        callback();
    }
    

    I use my waitfor() function in the following way:

    var _TIMEOUT = 50; // waitfor test rate [msec]
    var bBusy = true;  // Busy flag (will be changed somewhere else in the code)
    ...
    // Test a flag
    function _isBusy() {
        return bBusy;
    }
    ...
    
    // Wait until idle (busy must be false)
    waitfor(_isBusy, false, _TIMEOUT, 0, 'play->busy false', function() {
        alert('The show can resume !');
    });
    

提交回复
热议问题