An infinite loop in Javascript is a piece of code which executes indefinitely until the program is terminated.
Standard infinite loop using while
while(true) {
console.log('Hello!');
}
This program will print into the console Hello!Hello!Hello!Hello!
indefinitely.
Infinite loop with delay
The easiest way to create a javascript infinite loop with delay is to use the setInterval
method. Here is an example of an infinite loop with setInterval.
let helloCounter = 1;
setInterval(() => {
console.log(`Hello for the ${helloCounter} time`);
helloCounter++;
}, 5000);
This program will print Hello for the N time
every 5 seconds indefinitely.
Why would you need an infinite loop?
Let's say you want a button that changes its color every 5 seconds. For this, you'll need a method which executes every 5 seconds indefinitely. Let's look at the example below.
<!DOCTYPE html>
<html>
<head>
<title>Color Changing Button</title>
</head>
<body>
<button id="mybtn">Color changing button</button>
<script>
const co = ['red', 'green', 'blue', 'black', 'yellow'];
let colorIndex = 0;
setInterval(() => {
document.getElementById("mybtn").style.backgroundColor = co[colorIndex];
colorIndex = (colorIndex + 1) % co.length;
}, 5000);
</script>
</body>
</html>
You can check this example at codepen.