(JavaScript)

Simple reminder for me

Javascript test or wait for load or die

After some tries I fiddled this one...
Well, you can use promises or (dot)then chains or other constructs, too.
This is only a sketch and should work in most browsers, to detect if something is ready or not.

Yes, it's oldschool, even the var, unfancy, simply working ;-)


function waitingFor(count, delay, tries) {
    var el = document.querySelector('some-dom-element'), // match case
        count_local = count || 0,    // initial count value, or... ok only 0 makes sense here
        delay_local = delay || 200,  // initial delay value, or from function call
        tries_local = tries || 10;   // initial tries value, or from function call

    if (el && el.length) {
        // we have a match, do your stuff
        console.log('Yeah, match after: ' + count_local + ' of ' + tries_local);
    } else if (count_local < tries_local) {
        // we are not ready, let's try again
        setTimeout(function () {
            waitingFor(count_local + 1, delay_local, tries_local)
        }, delay_local);
        console.log('Try: ' + count_local + ' of ' + tries_local);
    } else {
        // ok... we give up, maybe inform the client now
        // or execute alternative stuff
        console.log('Sorry, no match after ' + count_local + ' tries');
    }
}

waitingFor(0, 100, 20);

 

or maybe shorter and reversed tries:


function waitingFor (delay = 200, tries = 10) {
    var el = document.querySelector('some-dom-element');

    setTimeout(function () {
        tries--;
        if (el && el.length) {
            // we have a match, do your stuff
            console.log('Yeah, match after: ' + tries);
        } else if (tries > 0) {
            // we are not ready, let's try again
            setTimeout(function () {
                waitingFor(delay, tries)
            }, delay);
            console.log('Try: ' + tries);
        } else {
            // ok... we give up, maybe inform the client now
            // or execute alternative stuff
            console.log('Sorry, no match');
        }
    }, delay);
}
waitingFor(100, 20);

If you like to be more fancy search for BING async/await function  or Google async/await function