setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
while()
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
If I use while(true)
to execute a specific statement, my browser either crashes(Firefox), lags(Opera), or the statement won't be executed(Chrome), but if I used setInterval()
with a fixed time of 0 seconds, everything works perfectly, even though its only 0 seconds, and while(true)
can't logically be faster than 0 seconds, but why does this happen?
while() example:
<!DOCTYPE html>
<html>
<body>
<div id="counter"></div>
<script>
var i = 0;
while (true)
{
document.getElementById("counter").innerHTML += i++;
}
</script>
</body>
</html>
setInterval() example:
<!DOCTYPE html>
<html>
<body>
<div id="counter"></div>
<script>
var i = 0;
setInterval(function() { counter() }, 0);
function counter()
{
document.getElementById("counter").innerHTML += i++;
}
</script>
</body>
</html>