Created
February 10, 2020 16:01
-
-
Save zoetrope69/e8bd2398cd294f60f48aa41cd97c80a7 to your computer and use it in GitHub Desktop.
Handling loading Moat Yield Intelligence with a promise and timeout
This file contains 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
export const MOAT_TIMEOUT = 1000; | |
const handleMoatYieldReady = resolve => { | |
// being extra careful that this API is available because | |
// we shouldn't trust Moat works as expected... | |
if (!window.moatPrebidApi) { | |
return resolve({ moatYieldUnavailable: true }); | |
} | |
const { setMoatTargetingForAllSlots } = window.moatPrebidApi; | |
if (setMoatTargetingForAllSlots) { | |
setMoatTargetingForAllSlots(); // set targeting for MOAT | |
} | |
return resolve({ moatYieldLoaded: true }); | |
}; | |
/* | |
This function returns a Promise and | |
can resolve in two ways: | |
1. if `window.moatYieldReady` is called by Moat | |
2. if Moat doesn't load in time (MOAT_TIMEOUT passes) | |
If either is called the other is cancelled out. | |
We can ensure if Moat isn't loaded in MOAT_TIMEOUT, | |
our adverts are still called. | |
*/ | |
const loadMoatYield = () => { | |
return new Promise(resolve => { | |
const timeoutId = setTimeout(() => { | |
resolve({ moatYieldTimedOut: true }); | |
}, MOAT_TIMEOUT); | |
window.moatYieldReady = () => { | |
clearTimeout(timeoutId); // reset timeout | |
handleMoatYieldReady(resolve); | |
}; | |
}); | |
}; | |
export default loadMoatYield; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment