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

от admin

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

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

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

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

Нужно, чтобы, если у элемента установлен определенный класс, скрипт не выполнялся, а, если этот класс отсутствует, то выполнялся.
Схематично так:

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

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

  • Вопрос задан более трёх лет назад
  • 40293 просмотра
  • Facebook
  • Вконтакте
  • Twitter

Petroveg

  • Facebook
  • Вконтакте
  • Twitter

Novitsky

Petroveg

Novitsky

Petroveg

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

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

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

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

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

Для второго: и третьего

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!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

ABORT JAVASCRIPT EXECUTION

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

METHOD 1) RETURN FALSE

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

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

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
THE WORKER SCRIPT
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) < . >.
Читать:
Как изменить размер объекта в blender

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

METHOD 5) WINDOW STOP

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, 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”.

EXTRA BITS & LINKS

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

LINKS & REFERENCES

    – Stack Overflow – Tutorials Point – Code Boxx – MDN – MDN | process.exit() – NodeJS – 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!

How to terminate the script in JavaScript?

How can I exit the JavaScript script much like PHP’s exit or die ? I know it’s not the best programming practice but I need to.

25 Answers 25

«exit» functions usually quit the program or script along with an error message as paramete. For example die(. ) in php

The equivalent in JS is to signal an error with the throw keyword like this:

You can easily test this:

Lorenz Lo Sauer's user avatar

Qantas 94 Heavy's user avatar

Ólafur Waage's user avatar

Even in simple programs without handles, events and such, it is best to put code in a main function, even when it is the only procedure :

This way, when you want to stop the program you can use return .

If you don’t care that it’s an error just write:

That will stop your main (global) code from proceeding. Useful for some aspects of debugging/testing.

There are many ways to exit a JS or Node script. Here are the most relevant:

If you’re in the REPL (i.e. after running node on the command line), you can type .exit to exit.

Dan Dascalescu's user avatar

Place the debugger; keyword in your JavaScript code where you want to stop the execution. Then open your favorite browser’s developer tools and reload the page. Now it should pause automatically. Open the Sources section of your tools: the debugger; keyword is highlighted and you have the option to resume script execution.

I hope it helps.

More information at:

rbelow's user avatar

Javascript can be disabled in devtools: ctrl+shift+j followed cltf+shift+p then type disable javascript

Possible options that mentioned above:

If page is loaded and you don’t want to debug crash or reload:

Additionally clear all timeouts

this removes scripts and recreates elements without events

If jQuery is not available on the webpage copy-paste source code into a console.

There’re might be other stuff. Let me know in a comment.

Hebe's user avatar

In my case I used window.stop .

The window.stop() stops further resource loading in the current browsing context, equivalent to the ‘stop’ button in the browser.

Because of how scripts are executed, this method cannot interrupt its parent document’s loading, but it will stop its images, new windows, and other still-loading objects.

Usage: window.stop();
(source)

ashleedawg's user avatar

In JavaScript multiple ways are there, below are some of them

Method 1:

Method 2:

Method 3:

Method 4:

Method 5:

write your custom function use above method and call where you needed

Note: If you want to just pause the code execution you can use

I think this question has been answered, click here for more information. Below is the short answer it is posted.

You can also used your browser to add break points, every browser is similar, check info below for your browser.

For Chrome break points info click here
For Firefox break points info click here
For Explorer break points info click
For Safari break points info click here

If you’re looking for a way to forcibly terminate execution of all Javascript on a page, I’m not sure there is an officially sanctioned way to do that — it seems like the kind of thing that might be a security risk (although to be honest, I can’t think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just return from whatever function is executing. (The return statement is optional if it’s the last thing in the function and the function shouldn’t return a value) If there’s some reason returning isn’t good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.

Note that in practice, most browsers’ Javascript interpreters will simply stop running the current script if they encounter an error. So you can do something like accessing an attribute of an unset variable:

and it will probably abort the script. But you shouldn’t count on that because it’s not at all standard, and it really seems like a terrible practice.

Похожие статьи