How to terminate a script in JavaScript ?
Last Updated :
17 Jan, 2024
To terminate a script in JavaScript, we have different approaches:
Method 1: Using return
In order to terminate a section of the script, a return statement can be included within that specific scope.
Example: Here, we are using return statement.
javascript
let i = 10;
// Return statement is in
// the global scope
if (i === 10)
return;let i = 10;
// Return statement is in
// the global scope
if (i === 10)
return;
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write('This section will not be executed');
document.write('<br>');
document.write(arr.filter(
(elem, index) => { return elem > 2 }));
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write('This section will not be executed');
document.write('<br>');
document.write(arr.filter(
(elem, index) => { return elem > 2 }));
Output:
In the absence of the return statement:
This section will not be executed
3, 4, 5, 6, 7, 8, 9
In the presence of return:
No output will be shown since the program is terminated on the encounter.
Method 2: Terminating a part of the Script
Example: Depending on a condition, a certain section of the script can be terminated using a "return" statement. The "return " statement returns "undefined" to the immediate parent scope, where the termination can be handled. This is the best practice since handling terminations makes it easier for future debugging and readability of the code.Â
javascript
function doSomeThing() {
let i = 10;
if (i === 10)
return;
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
'This section will not be executed');
console.log(arr.filter(
(elem, index) => { return elem > 2 }));
}
let i = doSomeThing();
if (i === undefined)
console.log('Terminated');
Output:
Terminated
Method 3: Throwing an error on purpose
Example: We deliberately throw an error to terminate the section of the script that we want to. It is best practice to handle the error using a "try-catch" block.Â
javascript
function doSomeThing() {
let i = 10;
if (i === 10)
throw new Error(
'Program Terminated');
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
'this section will not be executed');
console.log(arr.filter(
(elem, index) => { return elem > 2 }));
}
try {
doSomeThing();
}
catch (err) {
console.log(err.message);
}
Output:
Program Terminated
Method 4: Using process.exit for Node.JS applications
Example: There will be no other output, in this case since we exited the script. This is applicable to all JavaScript applications in the NodeJS environment. There are numerous other methods such as process.kill(process.pid) and process.abort() in NodeJS but process.exit() suffices for most of the cases, if not all cases.
javascript
function doSomeThing() {
let i = 10;
console.log('Terminating ');
process.exit(0);
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
'This section will not be executed');
console.log(arr.filter(
(elem, index) => { return elem > 2 }));
}
doSomeThing();
Output:
Terminating:
Method 5: Using clearInterval() method
The clearInterval() function in javascript clears the interval which has been set by the setInterval() function before that.
Syntax:
clearInterval(nameOfInterval);
Example: Here, Clicking the "Start Script" button initiates a repeating action every second using setInterval()
. Clicking the "Stop Script" button stops the repeating action by calling clearInterval(intervalId)
, where intervalId
is the ID returned by setInterval()
. The script logs "Repeating action..." to the console every second until you click "Stop Script," at which point it logs "Script stopped."
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Script Termination Example</title>
</head>
<body>
<button id="startButton">Start Script</button>
<button id="stopButton">Stop Script</button>
<script>
let intervalId; // Variable to store the interval ID
function repeatingAction() {
console.log("Repeating action...");
}
document.getElementById("startButton")
.addEventListener("click", function () {
// Start the repeating action every 1 second
intervalId = setInterval(repeatingAction, 1000);
});
document.getElementById("stopButton")
.addEventListener("click", function () {
// Stop the repeating action when the "Stop Script"
// button is clicked
clearInterval(intervalId);
console.log("Script stopped.");
});
</script>
</body>
</html>
Output:

Similar Reads
How to Set Time Delay in JavaScript?
Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
2 min read
How to stop setInterval Call in JavaScript ?
In JavaScript, the setInterval() function is used to repeatedly execute a specified function at a fixed interval. However, there may be scenarios where we need to stop the execution of setInterval() calls dynamically. Stopping a setInterval() call in JavaScript is essential to prevent ongoing repeti
2 min read
How to terminate execution of a script in PHP ?
In this article, we are going to discuss how to terminate the execution of a PHP script. In PHP, a coder can terminate the execution of a script by specifying a method/function called the exit() method in a script. Even if the exit() function is called, the shutdown functions and object destructors
2 min read
How to use the alert() method in JavaScript ?
In this article, we will learn how to use the alert() method in JavaScript. The alert() method is used to show an alert box on the browser window with some message or warning. We can use it as a message or as a warning for the user. Approach: To show an alert on the browser window, we make a button.
2 min read
How to set the cursor to wait in JavaScript ?
In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha
3 min read
How to stop forEach() method in JavaScript ?
Stopping a forEach() loop seems almost like an impossible task but here are a few tricks by which we might do it. Sample example using forEach(): var sum = 0; var number = [90, 4, 22, 48]; number.forEach(myFunction); function myFunction(item) { sum += item; } console.log(sum); Tricks to stop forEach
2 min read
How to use goto in Javascript ?
There is no goto keyword in javascript. The reason being it provides a way to branch in an arbitrary and unstructured manner. This might make a goto statement hard to understand and maintain. But there are still other ways to get the desired result. The method for getting the goto result in JavaScri
3 min read
JavaScript Continue Statement
The continue statement in JavaScript is used to break the iteration of the loop and follow with the next iteration. Example of continue to print only odd Numbers smaller than 10JavaScriptfor (let i = 0; i < 10; i++) { if (i % 2 == 0) continue; console.log(i); }Output1 3 5 7 9 How Does Continue Wo
1 min read
Control Statements in JavaScript
JavaScript control statement is used to control the execution of a program based on a specific condition. If the condition meets then a particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition. Types of Control Statements
3 min read
How to Wait n Seconds in JavaScript?
Here are the various methods to wait n seconds in JavaScript1. Using setTimeout() FunctionsetTimeout() is an asynchronous function in JavaScript that allows you to run code after a specific amount of time has passed. Since setTimeout() is a method of the window object, you can technically write it a
3 min read