0

I have the following JavaScript function.

function ready(interval, last_wait, el, callback) {
    if (jQuery(el).length) {
        console.log("Element ready: " + el)
        setTimeout(function () {
            callback(jQuery(el));
        }, last_wait);
    } else {
        console.log("Waiting element: " + el)
        setTimeout(function () {
            ready(interval, last_wait, el, callback);
        }, interval);
    }
};

It basically waits for a DOM element to exist. If it isn't, waits more interval milliseconds. What I want is adding a timeout parameter. If the function wait timeout milliseconds in total and the DOM element still doesn't appear, then just do nothing, stop waiting and return. I can't make it work because of the recursive nature of the function. I also considered using a global variable, but it seems not the correct way to do it. Hope someone could point me in the right direction.

1
  • I updated my answer to stop after 3 attempts Commented Dec 12, 2019 at 9:41

1 Answer 1

1

This works for me

If you increase the stopAfter, the code will run to conclusion

var tId, stopAfter = 3
const cb = el => el.html("Callback called");
function ready(interval, last_wait, el, callback) {
  if (stopAfter === 0) {
    clearInterval(tId);
    return;
  }
  if ($(el).length) {
    clearInterval(tId);
    console.log("Element ready: " + el)
    setTimeout(function() { callback($(el)); }, last_wait);
    return;
  }
  console.log("Waiting element: " + el)
  if (!tId) tId = setInterval(function() {
    stopAfter--;
    ready(interval, last_wait, el, callback);
  }, interval);
};

// testing the above
ready(1000,2000,"#div1",cb)
setTimeout(function() {     
  $("body").append(`<div id="div1">Div1</div>`) }
,5000); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

3 Comments

hi @mplungjan, thanks for you answer. Your implement uses stopAfter as a counter and it will wait that many times of interval. What I want is a parameter that will be waited for that long time. They are not exactly the same.
How not? If you wait 3 times 5 sec is it 15 secs!
Uh, yes. Let me think about it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.