How to terminate a script in JavaScript?


The termination of the script means that it stops executing the JavaScript code. In some emergency cases, developers requires to abort the execution of JavaScript code in the middle while the script is executing.

Also, we can use the if-else statement to decide when to terminate the script execution and when to continue. Here, we will learn different ways to terminate the script midway.

Use the Return Statement

The return statement is used to terminate the execution of any code inside the script. Once we execute the return statement inside the function, the code written after the return statement will not execute. However, we don’t need to return any value with the return statement, as we can just use the return keyword.

Syntax

Users can follow the syntax below to use the return statement to terminate the execution of the script in JavaScript.

function execute() {
   
   // this code will be executed
   return;
   
   // this code will not be executed.
}

In the above syntax, we have used the return statement with the function.

Example

In the example below, we invoke the execute() function whenever the document loads on the web page. Inside the execute() function, we check if the first value of the array exists and continue execution; Otherwise, we execute the return statement to stop the execution of the script.

<html>
<body>
   <h3>Using the <i> return statement </i> to terminate the script in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById("content");
      let array = [];
      function execute() {
         content.innerHTML = "This is a JavaScript code.";
         if (!array[0]) {
            return;
         }
         content.innerHTML = "This statment will not execute!";
      }
      execute();
   </script>
</body>
</html>

In the output, users can observe that the function's last statement is not executed as a condition of the if statement evaluating true, and the return statement is executed.

Throw an error to terminate a script

We can throw custom errors using the throw keyword. We can use the Error() constructor to create a new error. We can throw an error from anywhere inside the script to stop execution. When we throw an error, it will not execute statements written after the throw statements.

Syntax

Users can follow the syntax below to throw an error to terminate the execution of the script in JavaScript.

throw new Error("Error_Message"); 

In the above syntax, ‘Error_message’ is a message of the error to show to users.

Example

In the example below, we have thrown the error using the throw keyword from the execute() function. Also, we have triggered the function call inside the try-catch block to handle the errors. Users can observe in the output that the script will stop the execution after we throw an error.

<html>
<body>
   <h3>Throwing the <i> error </i> to terminate the script in JavaScript.</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById("content");
      let array = [];
      function execute() {
         throw new Error("This is an error to stop execution!");
         content.innerHTML += "This statement will not execute!";
      }
      try {
         execute();
      }
      catch (err) {
         content.innerHTML += "Error: " + err.message;
      }
   </script>
</body>
</html>

Use the clearInterval() method

The clearInterval() method takes the id of the timer as a parameter to clear the timer. We can set the timer to execute any function. For example, we can execute some scripts after some delay using the setTimeOut() method. If we require to stop the execution of the script, we can clear timeout using the clearInterval() method before the script executes.

Syntax

Users can follow the syntax below to use the clearInterval() method to terminate the execution of the script.

let timeVar = setTimeout(() => {
   
   // stop execution of this script
},delay);
clearInterval(timeVar);

In the above syntax, we can stop the execution of the script written inside the callback function of the setTimeOut() method.

Example

In the example below, we used the setTimeOut() method to execute the script after a delay of 2000 milliseconds. Also, we have stored the id of the timer inside the timeVar variable.

We clear the timer using the clearInterval() method before the script executes, and that is how we can stop the execution of any script in JavaScript.

<html>
<body>
   <h3>Using the <i> clearInterval() method </i> to terminate the script in JavaScript.</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById("content");
      let timeVar = setTimeout(() => {
         content.innerHTML = "This is inside the setTimeOut() function!";
      }, 2000);
      content.innerHTML = "This is outside the setTimeOut() function!";
      clearInterval(timeVar); // This will clear the setTimeOut() function.
   </script>
</body>
</html>

Use the process.exit() method in Node.js

The process.exit() will not work with vanilla JavaScript, and it will only work with Node.js as we need to import the ‘process’ module. We can execute the process.exit() method by passing 0 as a parameter to terminate the script.

Syntax

Users can follow the syntax below to use the process.exit() method to terminate the script.

process.exit(0); 

In the above syntax, we have passed 0 as a parameter for the termination purpose.

Example

In the example below, we have written the code of JavaScript. We have imported the processing module in the code. We have assigned 30 to the ‘num’ variable. The if statement condition always evaluates true, so it will stop the execution of the code, which we can observe in the output.

// Importing process module
var process = require('process');
let num = 30;
console.log("The value of number is " + num);
if(num > 20) {
   process.exit(0);
}
console.log("This line will not be printed as process.exit() is called"); 

We learned various approaches to terminate the script in JavaScript. The first way is using the return statement, the second is by throwing an error, the third is using the clearInterval() method, and the last is using the process.exit() method.

Using the return statement to terminate the script is best, but it will only work inside the function. The clearInterval() method only terminates the script immediately before the setTImeOut() method executes the script. The process.exit() is only helpful with NodeJS.

Updated on: 09-Mar-2023

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements