Skip to content

Instantly share code, notes, and snippets.

@bhavyaw
Created September 7, 2016 08:25
Show Gist options
  • Save bhavyaw/77bd0a04d99a7d7a4961b38844708957 to your computer and use it in GitHub Desktop.
Save bhavyaw/77bd0a04d99a7d7a4961b38844708957 to your computer and use it in GitHub Desktop.
Waiting for condition to get true and then executing a certain function
//**********************************************************************
// 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();
}
@bhavyaw
Copy link
Author

bhavyaw commented Sep 7, 2016

Usage is as follows :

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 !');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment