tags:

views:

2450

answers:

2

I neeed a code that will exit the js script much like PHP 'exit' or 'die'. (I know its not the best programming practice but I need it).

+6  A: 

Javascript equivalent for PHP's die

Hope it helps.

Btw its just calling exit() (thanks splattne)

Ólafur Waage
Here's the source code of exit: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_exit/
splattne
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.
andynormancx
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.
annakata
A: 

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:

function exit() {
    p.blah();
}

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.

David Zaslavsky
All that will do will stop the current executing bit of scripting. It won't stop new events from firing and running new bits of script.
andynormancx
True, that's what I meant.
David Zaslavsky
Not to mention, you don't need an extra bad function to throw an error. Javascript has a built-in throw statement.
Chris
The die function does a lot more than your p.blah(), it runs through the windows events and replaces the handles they have with "e.preventDefault();e.stopPropagation();", which will stop the events firing. _Then_ it throws an exception.
andynormancx