Detailed explanation of how to detect and prevent JavaScript infinite loops

Detailed explanation of how to detect and prevent JavaScript infinite loops

Preface

How is the Js dead loop caused? In fact, when we write code, if we don't pay attention or miss something, we will write an infinite loop, as shown in the following code:

If i++ is not written, this is an infinite loop. If you want to know the consequences of an infinite loop, you might as well try it yourself.

An infinite loop is a piece of JavaScript code that has an incorrect condition that prevents it from terminating the loop.

Infinite loops are dangerous because they can cause the environment in which you are running your code (browser or NodeJS server) to crash or freeze your computer, causing it to stop responding.

for and while statements are a common cause of an infinite loop, so this tutorial will help you understand how to detect and fix infinite loops caused by these statements.

Let's start by fixing the infinite loop in our for statement.

Fix infinite loop in for statement

A for statement can cause an infinite loop when you mistakenly put an assignment operator instead of a comparison operator in the second expression (in the conditional expression)

Following is an example of a for statement that will result in an infinite loop. Note how in the second expression i = 10:

for (let i = 0; i = 10; i++) {
  console.log("Infinite loop");
}

The for statement requires the second expression to evaluate to false to terminate the loop. In the above example, the assignment operator i = 10 is placed as the conditional expression instead of a comparison operator like i < 10 or i > 10.

Because the assignment operator always evaluates to true, the for statement will not stop printing "Infinite loop" to the console, which may cause your computer to freeze.

To fix the for statement above, you need to replace the second expression with something that can be reached by the for statement. An example is using comparison operators ( =<, <, >, >=)

// the second expression is replaced with <
for (let i = 0; i < 10; i++) {
  console.log("Infinite loop");
}

There is another version of the same error. This time, the first expression and the second expression result in an infinite loop:

for (let i = 5; i > 0; i++) {
  console.log("Infinite loop");
}

As you can see from the above code, the loop will continue as long as the variable i is greater than 0.

Since the value of i is already greater than 0 when it is initialized, the second expression will always evaluate to true, resulting in an infinite loop.

To fix the code above, the third expression must decrement i instead of incrementing its value:

for (let i = 5; i > 0; i--) {
  console.log("Infinite loop");
}

Another example of a for statement that could result in an infinite loop is when all three expressions within the parentheses are omitted, as follows:

for (;;) {
  console.log("Infinite loop");
}

But the code above should only be written on purpose, so unless you want your computer to crash, you should not use it in your projects.

Although the for statements you write will certainly be more complex than the examples above, you can still use the same principles to find and fix errors in for statements.

First, you need to make sure that the second expression you place inside the for statement can actually evaluate to false.

If the second expression is correct, start checking the first and third expressions. Does the first expression initialize a value that always evaluates to true when the second expression is executed?

Finally, does the third expression correctly increment or decrement the value of the variable initialized in the first expression?

To summarize: first check your second expression, then check the first and third expressions in that order.

Next, let's learn how to fix the infinite loop caused by the while statement.

Fix infinite loop in while statement

A while statement can cause an infinite loop if the conditional expression inside the parentheses always evaluates to true:

while (true) {
  console.log("Infinite loop");
}

To prevent an infinite loop, the while statement's conditional expression must evaluate to false.

One of the most common mistakes when writing a while statement is forgetting to modify the value of the variable used in the conditional expression.

Note how the value of never changes in the following example:

let i = 0;
 
while (i < 6) {
  console.log("Infinite loop");
}

You need to increment the value of i inside the body of the while statement so that the conditional expression evaluates to false when the loop executes:

let i = 0;
 
while (i < 6) {
  console.log("Infinite loop");
  i++;
}

No matter how complex your while statement is, you need to make sure that the conditional expression inside the while() parentheses can evaluate to false.

If you still can’t find what’s causing the infinite loop, you can use the console.log() statement to print the value of the variable used by the conditional expression:

let i = 0;
 
while (i < 6) {
  console.log("Infinite loop");
  i++;
  console.log(i);
}

The console log can help you pinpoint the errant line of code and fix it.

Summarize

This is the end of this article on how to detect and prevent JavaScript infinite loops. For more information on detecting and preventing js infinite loops, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to detect infinite loops in JavaScript with examples

<<:  How to install and use Ubuntu Docker

>>:  MySQL multi-instance deployment and installation guide under Linux

Recommend

How to use CSS to write different styles according to sub-elements

The effect we need to achieve: What is needed The...

jQuery plugin to implement minesweeper game (1)

This article shares the specific code of the firs...

Linux series of commonly used operation and maintenance commands (summary)

Table of contents 1. System monitoring 2. File Op...

HTML basics HTML structure

What is an HTML file? HTML stands for Hyper Text M...

How to set a dotted border in html

Use CSS styles and HTML tag elements In order to ...

Solution for installing opencv 3.2.0 in Ubuntu 18.04

Download opencv.zip Install the dependencies ahea...

Detailed explanation of Vue's monitoring properties

Table of contents Vue monitor properties What is ...

Detailed explanation of the basic use of Apache POI

Table of contents Basic Introduction Getting Star...

Analysis of the reasons why MySQL's index system uses B+ tree

Table of contents 1. What is an index? 2. Why do ...

Tips for Mixing OR and AND in SQL Statements

Today, there is such a requirement. If the logged...

The Complete Guide to Grid Layout in CSS

Grid is a two-dimensional grid layout system. Wit...

Detailed tutorial on configuring nginx for https encrypted access

environment: 1 CentOS Linux release 7.5.1804 (Cor...

Several common methods of sending requests using axios in React

Table of contents Install and introduce axios dep...

Vue+Bootstrap realizes a simple student management system

I used vue and bootstrap to make a relatively sim...