'How to identify and terminate a javascript in infinite loop programmatically?
It is more of a hypothetical question. There is sometimes a possibility of a javascript code entering an infinite loop and blocking everything specially in early stages of development. I know the best solution would be to code so that such a situation never arises but what if in a certain case it is impossible to write a fullproof code (maybe because we don't have control on the input or something else).
Is there any way we can programmatically determine when a code is in an infinite loop and terminate it?
Maybe running the pieces of code where such a thing could happen in a separate thread or in a child process synchronously and determining when that thread/process is in an infinite loop.
How could one go about doing that? Is it possible to determine when a thread (either main or child) is in an infinite loop by determining the CPU usage by that thread alone?
Based on the discussion had in comments below I realise that identifying a blocking infinite loop would be impossible on the basis of tracking repetitive execution of similar statements and high resource utilization alone. So I think that the solution lies in a combination of both. But that brings as back to our earlier problem. How can we gauge the CPU usage by a script?
Solution 1:[1]
For simple loops you can use approach used here . It uses path based approach to detect infinite loop. Statements are considered as nodes of graph.
You can also see this paper. They have implemented run time solution for java program.
Solution 2:[2]
Given there are no other viable/sophisticated solutions proposed, a low-tech solution is to just use a counter and abort if it reaches an absurdly high number.
This requires manual coding effort, but can be useful for debugging an infinite loop when you know it is already happening.
var count = 0
while(true){
if(count++>100000){
//assume infinite loop, exit to avoid locking up browser while debugging
break;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Glorfindel |
| Solution 2 | pythonjsgeo |
