Home > Web Front-end > JS Tutorial > How to terminate a script in JavaScript?

How to terminate a script in JavaScript?

王林
Release: 2023-09-04 10:29:02
forward
1077 people have browsed it

如何终止 JavaScript 中的脚本?

Termination of a script means it stops executing JavaScript code. In some emergency situations, developers need to abort the execution of JavaScript code during script execution.

Additionally, we can also use if-else statements to decide when to terminate script execution and when to continue. Here we will learn different ways to terminate a script midway.

Use Return Statement

The return statement is used to terminate the execution of any code within the script. Once we execute the return statement inside the function, the code following the return statement will not be executed. However, we don't need to use the return statement to return any value because we can just use the return keyword.

grammar

Users can use the return statement according to the following syntax to terminate the execution of scripts in JavaScript.

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

In the above syntax, we use the return statement in the function.

Example

In the example below, we call the execute() function every time the document is loaded on the web page. In the execute() function, we check if the first value of the array exists and continue execution; otherwise, we execute a 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>
Copy after login

In the output, the user can observe that the last statement of the function is not executed as a condition where the if statement evaluates to true and the return statement is executed.

Throw an error to terminate the script

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

grammar

Users can terminate the execution of scripts in JavaScript by throwing an error according to the following syntax.

throw new Error("Error_Message"); 
Copy after login

In the above syntax, "Error_message" is the error message displayed to the user.

Example

In the following example, we threw an error using the throw keyword in the execute() function. Additionally, we triggered a function call inside the try-catch block to handle the error. Users can observe in the output that the script will stop executing after we throw the 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>
Copy after login

Use clearInterval() method

The clearInterval() method takes the timer's id as a parameter to clear the timer. We can set timer to execute any function. For example, we can use the setTimeOut() method to execute some script after a delay. If we need to stop the execution of the script, we can use the clearInterval() method to clear the timeout before the script is executed.

grammar

Users can use the clearInterval() method according to the following syntax to terminate the execution of the script.

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

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

Example

In the example below, we use the setTimeOut() method to execute the script after a delay of 2000 milliseconds. Additionally, we store the timer's id in the timeVar variable.

We use the clearInterval() method to clear the timer before the script is executed, this is how we 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>
Copy after login

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

process.exit() does not work with normal JavaScript, it only works with Node.js because we need to import the "process" module. We can terminate the script by executing the process.exit() method passing 0 as argument.

grammar

Users can use the process.exit() method according to the following syntax to terminate the script.

process.exit(0); 
Copy after login

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

Example

In the following example, we wrote JavaScript code. We imported the processing module in our code. We have assigned 30 to the "num" variable. The if statement condition always evaluates to true so it will stop the execution of the code and we can observe this 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"); 
Copy after login

We learned about the various ways to terminate a script in JavaScript. The first method is to use the return statement, the second method is to throw an error, the third method is to use the clearInterval() method, and the last method is to use the process.exit() method.

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

The above is the detailed content of How to terminate a script in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template