Как остановить выполнение функции js
Перейти к содержимому

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

  • автор:

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

Аватар пользователя Ivan Gagarinov

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

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

return

Оператор return завершает выполнение текущей функции и возвращает её значение.

Интерактивный пример

Синтаксис

Выражение, значение которого будет возвращено. Если не указано, вместо него возвращается undefined .

Описание

При вызове оператора return в функции её выполнение прекращается. Указанное значение возвращается в место вызова функции. Например, приведённая ниже функция возвращает возведённое в квадрат значение своего аргумента, x (где x – это число):

Если возвращаемое значение не указано, вместо него возвращается undefined .

Следующие выражения всегда прерывают выполнение функции:

Автоматическая расстановка точек с запятыми

На выражение return влияет автоматическая расстановка точек с запятыми (ASI). Разрыв строки не допускается между ключевым словом return и выражением.

трансформируется ASI в:

В консоли появится предупреждение «unreachable code after return statement».

Примечание: Начиная с Gecko 40, предупреждение в консоли появляется, если обнаружен недостижимый код после return .

Для того, чтобы избежать данной проблемы (предотвратить ASI), можно использовать скобки:

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

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

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

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

  • Вопрос задан более трёх лет назад
  • 41490 просмотров
  • 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’)

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 .

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

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.

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

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

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

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

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 just want to stop further code from executing without «throwing» any error, you can temporarily override window.onerror as shown in cross-exit :

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *