Javascript прекратить выполнение скрипта

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.

The question is very simple and clear: it says «terminate the script». This means that the script is over. Finished. No more things should be expected to happen after that. It doesn’t mean just «terminate a function». A return from a function (as suggested here) is not a solution because there may follow other things that will occur after that and the programmer wants to cancel them! I think it’s very simple

25 Answers 25

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

die("sorry my fault, didn't mean to but now I am in byte nirvana") 

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

var m = 100; throw ''; var x = 100; x >>>undefined m >>>100 

@Sydwell : If you surround it by catch block, it will be caught and the program won’t terminate, defying the point here.

Don’t forget that you can add a message to the error: throw new Error(‘variable =’+x); It’s a nice way to quickly end a script while you’re working on it and get the value of a variable.

@ultimate I think that #Sydwell ment to wrap the whole script in try/catch, so you can get a) clean exit b) possible exception message when needed 🙂 Throwing uncought exceptions generally does not bring any good 🙂

function exit( status ) < // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brettz9.blogspot.com) // + input by: Paul // + bugfixed by: Hyam Singer (http://www.impact-computing.com/) // + improved by: Philip Peterson // + bugfixed by: Brett Zamir (http://brettz9.blogspot.com) // % note 1: Should be considered expirimental. Please comment on this function. // * example 1: exit(); // * returns 1: null var i; if (typeof status === 'string') < alert(status); >window.addEventListener('error', function (e) , false); var handlers = [ 'copy', 'cut', 'paste', 'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll', 'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput', 'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload' ]; function stopPropagation (e) < e.stopPropagation(); // e.preventDefault(); // Stop for the form controls, etc., too? >for (i=0; i < handlers.length; i++) < window.addEventListener(handlers[i], function (e) , true); > if (window.stop) < window.stop(); >throw ''; > 

That code doesn’t appear to stop events on elements from firing, just the window’s events. So you’d also need to loop through all the elements on the page doing something similar. It all sounds like a very odd requirement though.

Читайте также:  Span style margin top html

the whole die concept is a bit broken — the flow should be capable of handling any and all eventualities, whether that reqire try-catch or not.

You can’t stop XMLHttpRequest handlers. The current code does not stop intervals or timeouts from executing. Demo: jsfiddle.net/skibulk/wdxrtvus/1 You might consider this as a fix: stackoverflow.com/a/8860203/6465140

why does javascript need such convoluted hacks for basic, basic functionality that should just exist?

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 .

Works if you’re a poor programmer and don’t break your code into other functions. If you do, then a return inside a function that’s inside a function won’t do what you want.

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

// This will never exit! setInterval((function() < return; >), 5000); // This will exit after 5 seconds, with signal 1 setTimeout((function() < return process.exit(1); >), 5000); // This will also exit after 5 seconds, and print its (killed) PID setTimeout((function() < return process.kill(process.pid); >), 5000); // This will also exit after 5 seconds and create a core dump. setTimeout((function() < return process.abort(); >), 5000); 

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

I didn’t want to insult the intelligence of the readers by explaining an acronym that shows up as the first result of Googling it. I suggest you don’t mix JavaScript code with REPL commands because if a user copy/pastes that code block and runs it, they’ll get a Syntax error on the «.exit» line.

@Dan Expanding, or explaining, an acronym is definitely not any insult. The need to expand, or explain, an acronym depends on the individual reader. A reader who is unfamiliar with the acronym appreciates the explanation and finds the reading uninterrupted , whereas a reader who is familiar with the acronym becomes assured that the writer’s intent of the acronym matches the reader’s understanding.

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.

yes it could be helpful for people to know that you’re just forcing a ReferenceError by calling an undefined variable

For debugging purposes (because otherwise you don’t care), if one is to exit in a quick and «dirty» way, then better show a (recognizable) message with throw(message)

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

Possible options that mentioned above:

window.stop(); // equivalent to the 'stop' button in the browser debugger; // debugs for(;;); // crashes your browser window.location.reload(); // reloads current page 

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

$.xhrPool = []; $.xhrPool.abortAll = function() < $(this).each(function(i, jqXHR) < jqXHR.abort(); $.xhrPool.splice(i, 1); >); > $.ajaxSetup(< beforeSend: function(jqXHR) < $.xhrPool.push(jqXHR); >, complete: function(jqXHR) < var i = $.xhrPool.indexOf(jqXHR); if (i >-1) $.xhrPool.splice(i, 1); > >); 

this removes scripts and recreates elements without events

$('script').remove(); $('*').each(function()< $(this).replaceWith($(this).clone()); >); 

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

Читайте также:  Css выделить при наведении

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

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.

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

throw new Error("Something went badly wrong!"); 

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

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)

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

throw new Error("Stop script"); 

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

This is the answer I needed. A simple button that stops execution: the Chrome debugger’s Pause button.

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 :

function exit(code) < const prevOnError = window.onerror window.onerror = () => < window.onerror = prevOnError return true >throw new Error(`Script termination with code $.`) > console.log("This message is logged."); exit(); console.log("This message isn't logged."); 

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.

EDIT: OK, maybe this wasn't such a good answer in light of Ólafur's. Although the die() function he linked to basically implements my second paragraph, i.e. it just throws an error.

Источник

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

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

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

   

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

   

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

  

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

  

Источник

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

Для остановки выполнения JS кода на странице, можно сделать так:

  • Открыть DevTools и перейти на вкладку Sources;
  • Выбрать файл с логикой по которому будет вестись работа и найти необходимую строчку кода где необходимо поставить брейкпоинт;
  • Слева от строки находится столбец с ее номером. Если на него нажать, то появится синий значок — это и есть брейкпоинт того, чтобы использовать точку останова в DevTools;

add_breakpoint

Там же, кстати, ими можно и управлять:

  • Чтобы отключить брейкпоинт, достаточно убрать галочку рядом с ним
  • Удалить брейкпоинт можно с помощью нажатия на правую кнопку мыши около точки останова

manage_breakpoint

Еще бывают точки останова в коде, которые можно самостоятельно поставить в коде. Для создания такого брейкпоинта нужно просто вызвать debugger в коде. Этот подход эквивалентен предыдущему способу, через DevTools, только без использования визуального интерфейса.

console.log('a'); console.log('b'); debugger; console.log('c'); 

Еще есть вариант использовать throw. Инструкция throw позволяет генерировать исключения, определяемые пользователем. При этом выполнение текущей функции будет остановлено (инструкции после throw не будут выполнены), и управление будет передано в первый блок catch в стеке вызовов. Если catch блоков среди вызванных функций нет, выполнение программы будет остановлено.

const sayMeow(cat) =>  if (!cat.meow)  throw new Error('это не кот и он не умеет говорить мяу!'); > cat.meow() > 

Ну и наконец можно использовать точки останова в DOM, если вы собираетесь приостановить код, который изменяет узел DOM или его дочерние элементы. Это делается следующим образом:

  • Перейдите во вкладку Elements
  • Найдите элемент, на который нужно установить брейкпоинт
  • Нажмите на элемент правой кнопкой мыши
  • Наведите мышь на Break on, а затем выберите Subtree modifications, Attribute modifications или Node removal в зависимости от того, что вы хотите сделать. Ниже расскажем, что это такое и как работает.

dom_breakpoint

Более подробно про точки останова можно прочитать здесь, в интересной статье, на Хекслете.

Источник

Оцените статью