Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Make Javascript Stop?

Is it possible to make a Javascript script stop?

For example I have a simple condition that if true I want it to display an error and not run the rest of the script. I have accomplished this by just adding a random line in the condition at the end that throws a syntax error and makes it stop.

if (true) {
      document.write("Error");
       !StopHereNow!
}

This seems like a really bad solution but it works. After much searching around it's still the only solution I have but breaking something to make it stop seems very illogical.

Is there anything wrong with doing it this way?

Is there a better way?

Thanks

2 Answers

You can use 'break'

That just breaks out of the conditional statement but still continues to run the rest of the script after the condition.

I'm looking for something that just stops it completely from running any further code at all.

You can try to use 'return;'. It will stop execution of the current function. Throwing an error is also an option:

throw new Error('Error');

But if you have other functions that run after the one you'd "stopped" they would run regardless.

Stopping execution of everything is, AFAIK impossible. There are ways around (using promises, setInterval) but they basically stop the execution of the code, while JS is still running in the background.