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 location before watchPosition
has found its location.
Ideally the user would see a 'Waiting for location' message periodically until the location was obtained, then the form would submit.
However, I'm not sure how to implement this in JavaScript given its lack of a wait
function.
Current code:
var current_latlng = null; function gpsSuccess(pos){ //console.log('gpsSuccess'); if (pos.coords) { lat = pos.coords.latitude; lng = pos.coords.longitude; } else { lat = pos.latitude; lng = pos.longitude; } current_latlng = new google.maps.LatLng(lat, lng); } watchId = navigator.geolocation.watchPosition(gpsSuccess, gpsFail, {timeout:5000, maximumAge: 300000}); $('#route-form').submit(function(event) { // User submits form, we need their location... while(current_location==null) { toastMessage('Waiting for your location...'); wait(500); // What should I use instead? } // Continue with location found... });
You might need to wait for another function to complete, for a file to upload, or simply to make the user experience smoother. If you've got a Python program and you want to make it wait, you can use a simple function like this one: time. sleep(x) where x is the number of seconds that you want your program to wait.
Create a Simple Delay Using setTimeout log("Hello"); setTimeout(() => { console. log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!” to the console. And in many cases, this is enough: do something, wait, then do something else.
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 !'); });
Modern solution using Promise
function waitFor(conditionFunction) { const poll = resolve => { if(conditionFunction()) resolve(); else setTimeout(_ => poll(resolve), 400); } return new Promise(poll); }
Usage
waitFor(_ => flag === true) .then(_ => console.log('the wait is over!'));
or
async function demo() { await waitFor(_ => flag === true); console.log('the wait is over!'); }
References
Promises
Arrow Functions
Async/Await
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With