Wednesday, April 23, 2025

JavaScript While Loop

A while loop is a control flow statement that allows a block of code to be repeatedly executed as long as a certain condition is true.

The loop will continue to execute until the condition is no longer true, at which point the program will continue executing the rest of the code following the loop. The condition is checked at the beginning of each iteration of the loop, and if it is true, the code inside the loop is executed. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	var number = 0;
	
	while (number < 100) {
		document.write("Number at this moment: " + number + "<br>");
		number = number + 1;
	}
		
</script>
	
</body>
</html>

The code above shows an example of a while loop in JavaScript. In this case, the loop will continue executing as long as the value of the variable "number" is less than 100.

Inside the loop, the value of "number" is printed to the document using the document.write() function, along with some additional text. After printing the current value of "number", the value of the variable is incremented by 1 using the expression number = number + 1. This is necessary to ensure that the loop eventually terminates.

If a loop is not terminated properly, it will keep running indefinitely, causing what's called an infinite loop. This can be a serious issue, as it can crash the program or even the entire system if the loop consumes too many resources such as CPU or memory. It's important to ensure that loops are properly terminated with a condition that eventually becomes false or a statement that exits the loop when the desired goal is achieved.

Most modern browsers have protection against infinite loops. If a script runs for too long (e.g. due to an infinite loop), the browser will typically show a message asking the user if they want to stop the script. This is done to prevent the browser from becoming unresponsive and to protect against malicious scripts that could potentially crash the browser or execute other harmful actions.

There have been instances where malicious actors have used infinite loops as a form of denial of service attack. In such attacks, the malicious code contains an infinite loop that consumes all available resources of the browser or computer, making it unresponsive or causing it to crash. These attacks are often carried out as part of larger-scale attacks targeting websites or networks. To prevent such attacks, browsers and operating systems have implemented measures to detect and stop scripts that run for too long or consume too many resources.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...