Reputation: 19477
I have a page with a bunch of .... sections. In one of them, I get half way through it and decide I want to stop, and not run the rest of the contents of this script tag - but still run the other code segments on the page. Is there any way to do this without wrapping the entire code segment in a function call?
for example:
<script type='text/javascript'>
console.log('1 start');
/* Exit here */
console.log('1 end');
</script>
<script type='text/javascript'>
console.log('2 start');
console.log('2 end');
</script>
which should produce the output
1 start
2 start
2 end
and NOT 1 end
.
The obvious answer is to wrap the script in a function:
<script type='text/javascript'>
(function(){
console.log('1 start');
return;
console.log('1 end');
})();
</script>
Although this is usually the best approach, there are cases where it is not suitable. So my question is, what OTHER way can this be done, if any? Or if not, why not?
Upvotes: 6
Views: 4869
Reputation: 5542
If you want to stop the script tag using the throw
approach (mentioned in @knolleary's answer), but without throwing an error message in the console, here's a hacky way of doing it:
<script>
console.log("This will get logged to console.");
window.onerror = () => { window.onerror=undefined; return true; }
throw 0;
console.log("This won't.");
</script>
That code just captures the error with window.onerror
(returning true
hides the error).
You could of course create a global function if you need to use it often:
<script>
function scriptReturn() {
window.onerror = () => { window.onerror=undefined; return true; }
throw 0;
}
</script>
...
<script>
console.log("This will get logged to console.");
scriptReturn();
console.log("This won't.");
</script>
If you need to use window.onerror
elsewhere in your code you can use addEventListener
:
window.addEventListener("error", function(e) { ... })
Upvotes: 0
Reputation: 12854
You can use the break statement :
breakCode : {
document.write('1 start');
/* Exit here */
break breakCode;
document.write('1 end');
}
With a label reference, the break statement can be used to jump out of any code block
Reference
Upvotes: 6
Reputation: 10117
One way of achieving what you want (stopping execution of a given script block, without wrapping it in a function), is to throw an error.
<script type='text/javascript'>
console.log('1 start');
throw new Error();
console.log('1 end');
</script>
Of course the downside of this is that it will result in a error being logged to the console.
Upvotes: 2