James Coombes James Coombes - 4 months ago 24
Javascript Question

Loop more CPU friendly Js

The code will will alert 1 when the text in the element is rendered. (comes from external JSON bit slow to load). I have it working. The only down side is that it will keep running even when its true.

I would like the loop to keep checking if the text has render every 5 seconds and stop looping when its done.

setInterval(function() {
var text = $('#des1').text().length;
if (text > 1) {
setTimeout(function() {
var e = $("a.urlcouint").length
for (var t = 0; t < e; t++) {
var l = document.getElementById("xurl").href;
var n = l.indexOf("://") > -1 ? l.split("/")[2] : l.split("/")[0];
n = n.split(":")[0];
document.getElementById("xurl").innerHTML = n;
document.getElementById("xurl").setAttribute("id", "xurldone");
}
}, 5);
alert(1);
} else {
alert(0);
}
}, 2000);

Answer

You need to look at the clearInterval method

var interval = setInterval(function () {
// do something here
    // When a condition is met and you want to kill the timeout
    clearInterval(interval);
}, 2000);