0

A third-party js library was loading after some time after page load. Basically depends on it I have to call a method of it. The approach is checking the third party method using setInterval or setTimeout if it's the method (ag) available and then execute. The interval will run up to 10 times on every X second but if the method (ag) is available then stop the interval and execute the custom function.

$(document).ready( function () {

 setInterval(function () {
     if (typeof ag != 'undefined') { 
         // ag is available and execute your code here. 
         clearInterval();
     }
 }, 10);

}

Are there any better solutions?

EDIT 1:

Using above linked this answer -

function whenAvailable(name, callback) {
    var interval = 10; // ms
    window.setTimeout(function() {
        if (typeof name != 'undefined') {
            callback();
        } else {
            whenAvailable(name, callback);
        }
    }, interval);
}

whenAvailable("sp", function(t) {
    // do something
});

But how to set limits to execute max 10 times?

Charlie
  • 22,886
  • 11
  • 59
  • 90
Daniel Smith
  • 1,626
  • 3
  • 29
  • 59

1 Answers1

0

Below code worked for me. Just clear the interval when ag found or after 10 repetition.

var x = 0;
var intervalID = window.setInterval(function() {
    if (typeof ag != "undefined") {
        console.log('ag loaded!);
        window.clearInterval(intervalID);
        // do stuff
    }
    if (++x === 10) {
        console.log('complete 10 times');
        window.clearInterval(intervalID);
    }
}, 1000);
Charlie
  • 22,886
  • 11
  • 59
  • 90
Daniel Smith
  • 1,626
  • 3
  • 29
  • 59