I have an object used for interacting with an IndexedDB. It has a property ready that changes to 2 when the database has finished opening. How can I tell the read method to wait until this.ready == 2?
var db = {
open: function() {//a callback sets this.ready to 2 when the database has been successfully opened},
ready: 0,
read: function() {
if(!this.ready == 2) {//pause until this.ready == 2}
...
}
}
Should I write a function using setTimeout to check this.ready every 100 milliseconds or is there a more elegant solution?
A timeout (actually, probably an interval that cancels itself) is the only good way in JavaScript to “wait” for something. Otherwise, because there’s only a single thread, you end up blocking all other JS Execution in the browser. The other option would be to have something call your function when the status becomes a 2 (use a callback).
The “waiting” is approached like so: