Skip to content

Instantly share code, notes, and snippets.

@yowainwright yowainwright/observer.js
Last active Dec 14, 2017

Embed
What would you like to do?
ES5/6 Observer ๐Ÿ‘€
/*
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)
}

ES5/6 Observer

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.

/*
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
You canโ€™t perform that action at this time.