Reputation: 28572
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.
Upvotes: 0
Views: 193
Reputation: 177796
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>
Upvotes: 1