As browsers become more advanced, javascript engineering practices are stepping away from while loops and set intervals. However, if an older browser must be supported, have a simple observer to use can be beneficial to not be dependent on transpiling, etc.
Last active
December 14, 2017 02:26
-
-
Save yowainwright/e7eb194d60f17ff2661a20f9ba630e27 to your computer and use it in GitHub Desktop.
ES5/6 Observer π
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ES5/6 Observer π | |
--- | |
- Like a promise (sort of) but will work in older browsers | |
- With Babel, this will transpile to something very similar to want is written | |
- Note the error | |
- both callback, err will return empty strings by default | |
- bool is false by default | |
*/ | |
const observer = (bool = false, callback = () => '', iterator = 10, maxTime = 300, err = () => '') => { | |
const mT = maxTime | |
const it = iterator | |
let i, interval | |
const observe = () => { | |
i += 1 | |
// keep trying | |
if (bool === false && i < maxTime) return | |
// fail and warn | |
else if (i > maxTime) { | |
console.warn(`${bool} is false`) | |
return err() | |
} | |
// clear interval because bool is now true | |
// success callback | |
clearInterval(interval) | |
callback() | |
} | |
interval = setInterval(observe, 10) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ES5/6 Observer w/ While loop π | |
--- | |
- Like a promise (sort of) but will work in older browsers | |
- With Babel, this will transpile to something very similar to want is written | |
- Note the error | |
- both callback, err will return empty strings by default | |
- bool is false by default | |
*/ | |
const observer = (bool = false, callback = () => '', maxSeconds = 3, err = () => '') => { | |
const mS = maxSeconds | |
const it = iterator | |
const timer = new Date(); | |
let incomplete | |
while (!incomplete) { | |
const secondsPassed = timer.getSeconds() | |
if (secondsPassed > mS || bool) incomplete = true | |
if (bool) return callback() | |
else if (secondsPassed > mS && bool === false) { | |
console.warn(`${bool} is false`) | |
return err() | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment