ScriptsConnect ScriptsConnect - 1 year ago 97
Javascript Question

How to keep checking if JavaScript function is available, then call once available

My project consists of several files. I have a JavaScript function,

that is defined in a dojo require block in second.js, and my main jQuery is located in first.js. I have to keep the code separate because of using dojo and jQuery, as well as for other reasons. As a result, I'm not able to move my code around to prevent the issue I'm having.

When the page loads, first.js loads (call the function here), and then second.js (where the function exists) loads.

At the time I need to call window.toggleLayer() in first.js, it is not available, and I end up getting the following error:

TypeError: window.toggleLayer is not a function
window.toggleLayer(pKey, true);

What I ended up doing after finally figuring out the issue was a timing issue, I put setTimout around the function:

setTimeout(function () {
if(typeof window.toggleLayer == 'function'){
window.toggleLayer(pKey, true);
}, 1000);

The function now loads after 1 second. But as my project becomes heavier, 1 second will more than likely change. I can change this value to 2500 or higher, but this seems quite inefficient.

Is there a way to keep checking, dynamically, if the function exists? And if it exists, stop checking if it exists and then call it?

Answer Source

Try this:

function tryToggleLayer(){
  if(window.toggleLayer){ // check if function exists
    // If function exists, call it
    window.toggleLayer(pKey, true);
    // If not, try again in one second
    setTimeout(tryToggleLayer, 1000);


That way you can check if the function is ready every one second, using recursion

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download