Saturday, September 9, 2023
HomeSoftware DevelopmentCompletely different Methods to Abort JavaScript Execution

Completely different Methods to Abort JavaScript Execution


Aborting JavaScript execution may also help us to put in writing extra sturdy, safe, and environment friendly code by stopping sudden errors and behaviors.

Doable explanation why we have to abort JavaScript execution are:

  • We would have to abort execution when an error happens to forestall additional execution of the code and keep away from sudden habits or information corruption.
  • We would have to abort execution when consumer enter is invalid to forestall the code from working with incorrect or sudden enter.
  • We would have to abort execution in the course of a loop if a particular situation is met, or if we’ve discovered the end result we had been in search of.
  • We would have to abort execution in some instances to optimize efficiency, reminiscent of when utilizing setInterval or setTimeout, the place we would have to cease the execution of a perform or loop after a particular period of time.
  • In some instances, it is likely to be essential to abort execution to forestall malicious code from working, or to forestall delicate information from being accessed.

Other ways to abort JavaScript execution are as follows:

Utilizing the return assertion

Return statements in a programming language are used to skip the at the moment executing perform and return to the caller perform

Instance:

Javascript

perform checkNumber( num ) {

    if ( isNaN( num ) ) {

        return "Not a quantity!";

    }

    return num * 2;

}

  

console.log( checkNumber( "abc" ) );

console.log( checkNumber( 7 ) );

On this instance, the return assertion is used to abort the perform checkNumber if the enter just isn’t a quantity, and return the message “Not a quantity!”.

The break Assertion comes out of the loop when the situation is true. It breaks out of the loop or change. 

Instance:

Javascript

let fruits = [ "banana", "apple", "orange", "grape", "strawberry" ];

  

for (let i = 0; i < fruits.size; i++) {

    if (fruits[i] === "orange") {

        break;

    }

    console.log(fruits[i]);

}

On this instance, the break assertion is used to exit the for loop when the ingredient “orange” is discovered within the fruits array. The break assertion can be utilized to exit a loop or change assertion and cease the execution of the script.

The proceed assertion in Javascript is used to interrupt the iteration of the loop and follows with the following iteration. The break within the iteration is feasible solely when the desired situation going to happen.

Instance:

Javascript

let numbers = [ 1, 2, 3, 4, 5 ];

  

for (let i = 0; i < numbers.size; i++) {

    if (numbers[i] % 2 === 0) {

        proceed;

    }

    console.log(numbers[i]);

}

On this instance, the proceed assertion is used to skip the even numbers and print solely the odd numbers within the numbers array. The proceed assertion can be utilized to skip to the following iteration of a loop and abort the present iteration.

Utilizing the throw assertion

The throw assertion allows you to make your individual errors

Instance:

Javascript

perform checkAge( age ) {

    if ( age < 18 ) {

        throw "Have to be 18 or older";

    }

    console.log( "You might be allowed to enter" );

}

  

attempt {

    checkAge( 17 );

} catch ( error ) {

    console.log( error );

}

Output

Have to be 18 or older

On this instance, the throw assertion is used to throw an error and cease the execution of the perform checkAge if the enter age is lower than 18.

Utilizing the window.cease Technique

The cease() methodology in DOM is used to cease the window from loading sources within the present searching context, just like the browser’s cease button

Instance: We now have a webpage with some content material that takes a very long time to load, and also you need to give the consumer the power to cease the loading course of in the event that they get uninterested in ready. You’ll be able to add a “Cease” button to your web page and fix a click on occasion listener to it. Contained in the occasion listener perform, you may name the window.cease() perform to right away cease the loading course of.

HTML

<!DOCTYPE html>

<html>

<head>

    <title>Cease Loading Instance</title>

</head>

  

<physique>

    <h1>Loading Instance</h1>

    <p>This web page is taking a very long time to load....</p>

    <button id="stop-btn">Cease Loading</button>

  

    <script>

        const stopBtn = doc.getElementById('stop-btn');

        stopBtn.addEventListener('click on', () => {

            window.cease();

        });

    </script>

</physique>

    

</html>

Within the above instance, when the consumer clicks the “Cease Loading” button, the window.cease() perform is named, which instantly stops the loading course of and shows no matter content material has already been loaded on the web page. This may be helpful for bettering the consumer expertise on slow-loading pages.

The clearTimeout() and clearInterval strategies in javascript clear the timeout which has been set by the setTimeout() and setInterval features earlier than that.

Instance: 

Javascript

let timeoutId = setTimeout(perform () {

    console.log("This message will probably be logged after 3 seconds");

}, 3000);

  

clearTimeout(timeoutId);

  

let depend = 0;

let intervalId = setInterval(perform () {

    depend++;

    console.log("Rely is now:", depend);

}, 1000);

  

setTimeout(perform () {

    clearInterval(intervalId);

    console.log("Interval has been cleared");

}, 5000);

Output

Rely is now: 1
Rely is now: 2
Rely is now: 3
Rely is now: 4
Interval has been cleared

Within the above instance, we first use setTimeout to execute a perform after 3 seconds. Nevertheless, we instantly cancel the timeout utilizing clearTimeout, so no message will probably be logged to the console.

Subsequent, we use setInterval to execute a perform each second, which increments a depend variable and logs its worth to the console. After 5 seconds have handed, we use clearInterval to cancel the interval and log a message indicating that the interval has been cleared. Because of this, we see the depend enhance to five earlier than the interval is cleared, after which the message “Interval has been cleared” is logged to the console.

Conclusion: Thus, selecting the suitable methodology to abort JavaScript execution is dependent upon the particular use case and what you need to obtain. It is best to rigorously take into account the implications of every methodology and select the one that most closely fits your wants.

Final Up to date :
24 Jul, 2023

Like Article

Save Article



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments