Остановить выполнение кода javascript

Как остановить выполнение функции js

Чтобы остановить выполнение функции, достаточно просто вызвать инстркуцию return . Например:

const func = (num) =>  // если переданное число равно 2, то останавливаем работу функции if (num === 2)  return; > console.log('hello'); >; func(1); // => hello func(2); 

В примере выше, если вызвана функция с параметром 2, то срабатывает условие и функция прерывается благодаря return . Также можно вернуть результат из функции:

const func = (num) =>  // если переданное число равно 2, то останавливаем работу функции if (num === 2)  return 'is number 2'; > return 'hello'; >; console.log(func(1)); // => hello console.log(func(2)); // => is number 2 

Источник

Как остановить выполнение js-скрипта?

Вот, как это записать на JS?
Подскажите, пожалуйста.

P. S. Да, совсем забыл. Класс «disabled» подставляется автоматически, совсем другим скриптом.

Petroveg

if (проверяем состояние кнопки) < // Запускаем что-то >

Novitsky

Petroveg

Novitsky

Petroveg

Вам следует знать, что форму отправить может не только клик на кнопке. Попытка остановить отправку формы отслеживанием клика — признак новичка.

Самый простой и верный путь — правильно использовать атрибуты элементов форм jsfiddle.net/petroveg/qoh0oft5/5

Но уж если так хочется именно с классами, то jsfiddle.net/petroveg/qoh0oft5/6
Вариант однозначно хуже, ибо вы должны отслеживать кнопку при отправке, тогда как в первом варианте атрибут disabled уже сам по себе предотвращает отправку формы любым пользовательским способом.

Ну и самый отвратный вариант — тип кнопки button. Придётся и отправку, и клик отслеживать jsfiddle.net/petroveg/qoh0oft5/7

Управление состоянием кнопок для первого случая:

function manageButton (status)
function manageButton (status) < var $button = $(document.forms).filter('[data-container="order"]').find('[data-action="order"]'); if (status) < $button.addClass('disabled'); >else < $button.removeClass('disabled'); >>

Novitsky

@Petroveg: Спасибо большое! Буду разбираться и думать.
Насчет классов. Они нужны только для того, чтобы при нажатии на кнопку, при незаполненных полях, рамка у них становилась красная. Для этого есть скрипт: jsfiddle.net/429rwg1t и в нем используются именно классы. С атрибутом disabled этот трюк не пройдет.

Вот живой пример, с которым я борюсь: novi.co/test/bionica
Там, если наверху нажать на кнопку «Заказать обратный звонок» во всплывающем окне будет форма. В ней, если нажать на button при незаполненных полях, они подкрасятся красным.
А борюсь я с формой которая не в окне, а просто на странице. Там если нажать на кнопку всплывает окошко с сообщением об успешной отправке, даже при незаполненных полях.
Вот я и хочу, чтобы и поля подкрашивались в красный цвет, и сообщение об отправке всплывало, но только при заполненной форме.
Осложняется это тем, что за это отвечают разные скрипты.

Rad1calDreamer

Petroveg

@Romeo_viruS: вы точно уверены, что вот это:
.is(‘.test’)
длинней, чем
hasClass(‘test’)

Источник

6 Ways To Abort Javascript Execution (Simple Examples)

Welcome to a tutorial on how to abort Javascript execution. Need to manually stop a piece of script for some reason?

  1. In a function, simply return false or undefined .
  2. Manually throw new Error(«ERROR») in a function.
  3. Set a function to run on a timer – var timer = setInterval(FUNCTION, 1000) . Then clear it to stop – clearInterval(timer)
  4. Run the script with workers that can be terminated.
  5. Use window.stop() to prevent the page from loading and running.
  6. For NodeJS only – Use process.abort() or process.exit() .

But just how does each method work? Let us walk through some examples in this guide. Read on to find out!

TLDR – QUICK SLIDES

How To Abort Javascript Execution

TABLE OF CONTENTS

ABORT JAVASCRIPT EXECUTION

All right, let us now go through all the possible methods to stop or abort Javascript execution.

METHOD 1) RETURN FALSE

function test () < // (A) DO YOUR STUFF AS USUAL console.log("Test started"); let i = 0; i++; // (B) ABORT - RETURN "UNDEFINED" if (i != 0) < return; >// (C) RETURN RESULT IF OK console.log("This part will not run"); return i; > // (D) FIRE TEST() let i = test(); console.log(i); // (E) BEST TO HANDLE THE ABORTION GRACEFULLY if (i==undefined) < // HANDLE ABORT >

This is one of the most graceful and “non-hacker” ways that I will recommend using – Just return false or return undefined in the function. It should be very straightforward and easy to understand, even for beginners.

P.S. You might also want to handle what happens after the abortion. Maybe show an “error” message or something.

METHOD 2) THROW EXCEPTION

function test () < // (A) DO YOUR STUFF AS USUAL console.log("Test started"); let i = 0; i++; // (B) ABORT - THROW ERROR if (i != 0) < throw new Error("Manual Abort Script"); >// (C) RETURN RESULT IF OK console.log("This part will not run"); return i; > // (D) BEST TO TRY-CATCH FOR A GRACEFUL SCRIPT try < let x = test(); >catch (err)

Moving on, this is a “popular” method that I found on the Internet. Yep, it is funky to throw an “error” when it is not actually an error… But this is a guaranteed way to abort and stop scripts from proceeding any further. To not “crash” the script altogether, it is recommended to use a try-catch block to handle things gracefully – Maybe show the user a “script aborted” notification.

P.S. I will still recommend using the above return; or return false; instead – It is “softer” and “logically correct”.

METHOD 3) TIMER STOP

// (A) SET TIMER & RUN var timer = setInterval( () => console.log("Running"), 3000 ); // (B) "FORCE" ABORT IMMEDIATELY clearInterval(timer); // (C) OR SET A "TIMEOUT" setTimeout(() => < clearInterval(timer); console.log("Stopped"); >, 1000);

This is yet another one that I found on the Internet. The whole idea of this method is to put the script on a timer, and simply call clearInterval() to abort it. While it works, it is also kind of useless unless you have a script that runs in a loop or timer…

METHOD 4) WORKER TERMINATE

4A) WHAT ARE WORKERS?

For you beginner code ninjas who have not heard of workers – This is basically the Javascript way to do multithreading, allowing scripts to run in the background, allowing multiple scripts to run in parallel. If you want to learn more, I will leave a link to my other worker tutorial in the extras section below.

4B) THE MAIN SCRIPT

// (A) CREATE NEW WORKER var theWorker = new Worker("4b-worker.js"); // (B) WHEN THE WORKER IS DONE theWorker.onmessage = evt => < console.log("Worker script has completed."); console.log(evt.data); >; // (C) SEND DUMMY DATA TO WORKER // ! WORKER SCRIPT CANNOT ACCESS DOM DIRECTLY ! theWorker.postMessage(< Name : "John Doe", Email : "john@doe.com" >); // (D) ABORT AND TERMINATE WORKER // theWorker.terminate();

THE WORKER SCRIPT

// (A) START ONLY WHEN DATA RECEIVED onmessage = evt => < // (B) DATA RECEIVED console.log("Worker has received data and started."); console.log(evt.data); // (C) DO PROCESSING HERE // . // (D) REPLY RESULT postMessage(< status: 0, message: "OK" >); >;

THE EXPLANATION

  • First, we start by creating a new worker var theWorker = new Worker(«4b-worker.js») in the main script.
  • Take extra note that worker scripts have no access to the DOM tree. I.E. document.getElementByXX() will not work in 4b-worker.js .
  • This is why we have to send data to the worker in the main script – theWorker.postMessage( . );
  • Next in the worker script, we begin processing only when data is received – onmessage = function (evt) < . >.
  • When the worker is done, it returns a message back to the main script – postMessage( . ) .
  • Finally, back in the main script, we handle when the worker is done – theWorker.onmessage = function (evt) < . >.

As for the best part, we can abort the worker at any point in time using theWorker.terminate() .

METHOD 5) WINDOW STOP

// (A) DO YOUR STUFF var first = 123; var second = 456; var third = first + second; console.log(third); // (B) STOP LOADING window.stop(); console.log("This will still run. ");
console.log("THIS WILL NOT RUN");

Just use the window.stop() to stop the rest of the page from loading… Yep, it kind of works, and will stop all other scripts from loading/running. But as you might have guessed, this will also stop the HTML page from fully loading. 😐 Not really useful, unless you want to do an “emergency brake”.

METHOD 6) NODEJS ABORT & EXIT

// THIS IS FOR NODEJS ONLY // (A) DO YOUR STUFF var first = 123; var second = 456; var third = first + second; console.log(third); // (B) ABORT OR EXIT // ABORT = IMMEDIATE (ROUGH) // EXIT = AS QUICKLY AS POSSIBLE (GRACEFUL) // process.abort(); process.exit(); console.log("THIS WILL NOT RUN");

This is for NodeJS only, use the process.abort() and process.exit() functions to stop the execution. The difference between them is that abort() will stop immediately, and exit() will stop as soon as possible… That is, exit() is more graceful with the cleaning up, and not an abrupt “suddenly stop everything”.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

  • How to terminate the script in JavaScript? – Stack Overflow
  • How to stop the execution of a function with JavaScript? – Tutorials Point
  • Javascript Multithreading – Workers For Beginners – Code Boxx
  • Worker Terminate – MDN
  • Error – MDN
  • process.abort() | process.exit() – NodeJS
  • Window.stop() – MDN

TUTORIAL VIDEO

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “6 Ways To Abort Javascript Execution (Simple Examples)”

Thanks, the info about throwing an Error() was what I needed. I was trying to terminate execution inside a file that gets minimized before it ends up in a full file; but a return statement without appearing to be in a function was making the minimizer get confused. Error() seems to be the solution. Cheers

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Остановить выполнение скрипта | JavaScript

Прервать работу скрипта или в чём разница между return; return false; return true;

Если не нужно знать достигла ли функция положительного исхода, то достаточно указать return без значения:

   

Если дальнейшее выполнение скрипта должно прерываться (или развиваться по другому пути) при достижении положительного исхода рассматриваемой функции, то return присваивается значение, чаще false или true :

   

Как использовать return, когда функция вызывает саму себя (рекурсия)

  

Возврат массива из функции

  

Источник

Читайте также:  Php удаление дублей массивов
Оцените статью