Skip to content

Instantly share code, notes, and snippets.

@dreamyguy
Last active February 12, 2019 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c to your computer and use it in GitHub Desktop.
Save dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c to your computer and use it in GitHub Desktop.
For when you want to run a function but don't know when it's going to be defined. Keep checking until you WIN!
/* ===================================
* Scenario:
* You want to run a function but don't know when it's going to be defined.
* You keep checking if it's defined every 0.25 seconds. When it's defined, stop checking.
*
* Copyright (c) 2018, Wallace Sidhrée
* MIT License
====================================== */
// On doc ready for modern browsers
document.addEventListener('DOMContentLoaded', (e) => {
// Scope all logic related to what you want to achieve by using a function
const waitForMyFunction = () => {
// Use a timeout id to identify your process and purge it when it's no longer needed
let timeoutID;
// Check if your function is defined, in this case by checking its type
if (typeof myFunction === 'function') {
// We no longer need to wait, purge the timeout id
window.clearTimeout(timeoutID);
// 'myFunction' is defined, invoke it with parameters, if any
myFunction('param1', 'param2');
} else {
// 'myFunction' is undefined, try again in 0.25 secs
timeoutID = window.setTimeout(waitForMyFunction, 250);
}
};
// Initialize
waitForMyFunction();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment