PDA

View Full Version : Throwing an error to abort javascript execution


jayapalchandran
11-10-2009, 06:37 AM
Hi,
I call a javascript function b from another function a.
in the function b at certain conditions i want to stop the javascript execution and i have did it by throwing an exception by using Throw New Error('Stopi').
It is working well.

Is it good to stop the execution of javascript abruptly.
Is it bad if the functions are not returned to the calling function and finally to the operating system.
I will there be a over flow of stack or will stack keep increasing if i am throwing many such errors.


Meanwhile IE shows the yellow exclamation icon in its status bar as usual that there is a javascript exception. When you click that you can see the error description as 'Stopi' which i have thrown.

Here is an example...

<input type='text' name='name' id='name' />

function validate()
{
isempty('name','Please enter your name');
// no if condition or return statement here
}

function isempty(src,msg)
{
var so = document.getElementById(src)
if(so.value=='')
{
alert(msg)
so.focus()
throw new Error('Stopi')
}
}

so i dont have to use if condition when validating. no braces, no return statement, and no need to call focus for every if condition so this code reduces 6 lines and multiplied by number of input controls you are going validate. so i just need to call isempty and if the control has empty value then the user will get an alert and the execution stops.

Please suggest.

jayapalchandran
05-05-2011, 10:20 PM
Here is the one i am using like the above.

http://vikku.info/codesnippets/javascript/forcing-javascript-to-abort-stop-javascript-execution-at-any-time/

Kor
05-06-2011, 09:43 AM
My Goodness! You have returned after two years to post the solution? You have worked two years for that? I appreciate that... :)

By the way, I guess you could have simply used a return command to stop the execution of a code :)

jayapalchandran
05-06-2011, 10:28 AM
I thought of revamping this concept but still in the same place.

Besides you said to use return. That is not the case where i want a code.

I want javascript to terminate its execution at any line of code or at any moment.

This will not disable javascript but will stop the execution for that instance.

So after you do another event it will resume its work.

I have explained in my code that the situation like be even in side a loop or inside a deep nested function.

For those cases this code will be really helpful.

Kor
05-06-2011, 12:05 PM
return does exactly what you want. It stops the code at any line, at any moment. There is also break, to stop the execution of a loop and jump outside.

I still don't understand what you want. Maybe you could post a practical example, or something like this.

jayapalchandran
05-06-2011, 05:38 PM
Sorry that i haven't posted the code that would explain what i want. I will do it in a few days. Thank you for your response. i will be back here.