Reputation: 401
I have created this infinite loop in javascript, in order to run a setTimeout function. The problem is that, by doing this, my page doesn't even load in the first place.
Here is the javascript code:
function blurDiv() {
console.log("here");
rankingList.style.filter="blur(0.7)";
}
function loadContent() {
console.log("loaded");
$( "#ranking-container" ).load("index.php #ranking-list");
rankingList.style.filter="blur(0)";
}
while(true) {
setTimeout(blurDiv, 4000);
setTimeout(loadContent, 5000);
}
I was expecting that the loop would only run another iteration after those 5 seconds.
Upvotes: 1
Views: 516
Reputation: 8558
Use setInterval()
instead of while(true){setTimeout()}
function blurDiv() {
console.log("here");
// Other stuff here
}
function loadContent() {
console.log("loaded");
// Other stuff here
}
setInterval(blurDiv, 5000);
setInterval(loadContent, 5000);
Explanation:
setTimeout()
is an async function which means JS does not wait for it to complete and continues to run. Therefore, with the loop while(true)
, it creates two timeout callbacks in every turn which will result in a huge amount (a really huge amount) of timeout callbacks and will never get out of that while(true)
loop.
However, by using setInterval()
you create a timer that will fire the callback in every cycle (interval).
Upvotes: 5
Reputation: 178255
You can use setInterval (see other answer) or a callback
function loadIt()
$("#ranking-container").load("index.php #ranking-list",function() {
rankingList.style.filter="blur(0.7)";
setTimeout(loadIt,4000)
});
rankingList.style.filter="blur(0)";
}
loadIt();
Upvotes: 1
Reputation: 766
Harun's answer is sufficient to solve your issue. Additionally, if you want to know more about why you were getting that behaviour, it is due to something called the Event Loop
.
Check out this awesome video by Jake Archibald.
Upvotes: 2