Search code examples
javascripttimeoutwait

How can I add a timeout parameter to this JavaScript function?


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.


Solution

  • 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>