对象已移动

可在此处找到该文档 Different Ways to Abort JavaScript Execution – New Self New Life
New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

Different Ways to Abort JavaScript Execution

by admin
2 years ago
in Softwares
Best Coding Practices For Rest API Design
Share on FacebookShare on Twitter


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

Attainable the explanation why we have to abort JavaScript execution are:

  • We would have to abort execution when an error happens to stop additional execution of the code and keep away from surprising habits or information corruption.
  • We would have to abort execution when consumer enter is invalid to stop the code from operating with incorrect or surprising enter.
  • We would have to abort execution in the midst of a loop if a selected situation is met, or if we’ve discovered the consequence we have been on the lookout for.
  • We would have to abort execution in some instances to optimize efficiency, corresponding to when utilizing setInterval or setTimeout, the place we would have to cease the execution of a operate or loop after a selected period of time.
  • In some instances, it is likely to be essential to abort execution to stop malicious code from operating, or to stop delicate information from being accessed.

Alternative ways to abort JavaScript execution are as follows:

Utilizing the return assertion

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

Instance:

Javascript

operate 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 operate 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 aspect “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 subsequent iteration. The break within the iteration is feasible solely when the required 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 subsequent iteration of a loop and abort the present iteration.

Utilizing the throw assertion

The throw assertion allows you to make your personal errors

Instance:

Javascript

operate 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 operate 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 assets within the present shopping context, much like the browser’s cease button

Instance: We’ve 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 bored with ready. You may add a “Cease” button to your web page and connect a click on occasion listener to it. Contained in the occasion listener operate, you’ll be able to name the window.cease() operate 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() operate 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(operate () {

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

}, 3000);

  

clearTimeout(timeoutId);

  

let depend = 0;

let intervalId = setInterval(operate () {

    depend++;

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

}, 1000);

  

setTimeout(operate () {

    clearInterval(intervalId);

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

}, 5000);

Output

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

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

Subsequent, we use setInterval to execute a operate 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. In consequence, 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. You need to rigorously contemplate 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



Source link

Tags: AbortexecutionJavaScriptWays
Previous Post

Threads Sees Significant Decline in Usage, but Opportunity for Disruption Remains

Next Post

Come on, load faster! How to make images responsive?

Related Posts

Windows’ infamous ‘blue screen of death’ will soon turn black
Softwares

Windows’ infamous ‘blue screen of death’ will soon turn black

by admin
June 28, 2025
User Guide for Unopim Odoo Connector
Softwares

User Guide for Unopim Odoo Connector

by admin
June 27, 2025
Warp 2.0 evolves its terminal experience into an Agentic Development Environment
Softwares

Warp 2.0 evolves its terminal experience into an Agentic Development Environment

by admin
June 25, 2025
Huawei Cloud rolls out Pangu Models 5.5 to cover more industries
Softwares

Huawei Cloud rolls out Pangu Models 5.5 to cover more industries

by admin
June 24, 2025
Minor update(4) for Vivaldi Android Browser 7.4
Softwares

Minor update(4) for Vivaldi Android Browser 7.4

by admin
June 21, 2025
Next Post
Come on, load faster! How to make images responsive?

Come on, load faster! How to make images responsive?

10 Most Popular Movies Right Now: What to Watch In Theaters This Week (July 2023)

10 Most Popular Movies Right Now: What to Watch In Theaters This Week (July 2023)

  • Trending
  • Comments
  • Latest
Pamela Anderson raves about new natural, makeup-free look: ‘It’s freedom’

Pamela Anderson raves about new natural, makeup-free look: ‘It’s freedom’

October 8, 2023
Alec Baldwin indicted again for ‘Rust’ shooting that left cinematographer dead – National

Alec Baldwin indicted again for ‘Rust’ shooting that left cinematographer dead – National

January 21, 2024
A look into CAMPUS, ShopBack’s new Singapore HQ at Pasir Panjang

A look into CAMPUS, ShopBack’s new Singapore HQ at Pasir Panjang

July 2, 2022
User Manual for Odoo Docx Report Builder

User Manual for Odoo Docx Report Builder

November 30, 2024
Aaron Rodgers returns to ‘Pat McAfee Show’ 1 day after being axed by host – National

Aaron Rodgers returns to ‘Pat McAfee Show’ 1 day after being axed by host – National

January 11, 2024
Bones: All Of Brennan’s Interns, Ranked

Bones: All Of Brennan’s Interns, Ranked

June 15, 2021
Spinning and weaving with Stella Rose

Spinning and weaving with Stella Rose

January 22, 2024
18 Best Political Series on Netflix, Ranked

18 Best Political Series on Netflix, Ranked

March 25, 2025
Warner Bros. Gives Up on ‘Akira’ Remake, But Hollywood Won’t

Warner Bros. Gives Up on ‘Akira’ Remake, But Hollywood Won’t

June 28, 2025
Hulu Schedule June 30 – July 6, 2025: New TV Shows & Movies Being Added

Hulu Schedule June 30 – July 6, 2025: New TV Shows & Movies Being Added

June 28, 2025
Oscar-winner Marion Cotillard and partner Guillaume Canet split after 18 years together

Oscar-winner Marion Cotillard and partner Guillaume Canet split after 18 years together

June 28, 2025
Trump Backs Meta in Dispute Over Canada’s Digital Services Tax

Trump Backs Meta in Dispute Over Canada’s Digital Services Tax

June 28, 2025
Quavo Slaps Reporter’s Camera for Asking Question About Diddy

Quavo Slaps Reporter’s Camera for Asking Question About Diddy

June 28, 2025
All the glamorous celebrity looks from the Jeff Bezos, Lauren Sánchez wedding – National

All the glamorous celebrity looks from the Jeff Bezos, Lauren Sánchez wedding – National

June 28, 2025
How to share your Wi-Fi password across iPhones, Androids and other devices

How to share your Wi-Fi password across iPhones, Androids and other devices

June 27, 2025
Don't Call It a Comeback: Progressive House Never Left, and It's Recapturing Festival Glory

Don't Call It a Comeback: Progressive House Never Left, and It's Recapturing Festival Glory

June 27, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • Warner Bros. Gives Up on ‘Akira’ Remake, But Hollywood Won’t
  • Hulu Schedule June 30 – July 6, 2025: New TV Shows & Movies Being Added
  • Oscar-winner Marion Cotillard and partner Guillaume Canet split after 18 years together
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

New Self New Life