0

I was running through some while loops within my JavaScript code, and became curious as to what caused the loop to remove all the code from the website (except a single header). I figured it was due to the fact that the loop is infinite (since 1 will always equal 1), but was curious as to why it didn't just crash the website. Is it due to the document.write not being specified to a certain path?

javascript: (function() { while (1) {  document.write('Y'); }})();

Edit: Thanks for the help, it does seem that document.open was run and caused the page's code to be deleted. The browser then thought this was due to the actual website's code, and Chrome brought forth an error message.

  • Hard to tell what the exact question is. Why did it overwrite the entire page? Why do you not see a lot of Ys on the page? A while loop often results in the browser stopping the JS engine and giving you an option to stop the page, I'd call that a crash like event – Juan Mendes May 06 '19 at 14:21

1 Answers1

5

document.write() is a DOM blocking function, that means, the browser interrupts parsing. So when your function is called, the browser is stuck on it forever and does not go on rendering the site properly.

Another effect is the following:

as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.

https://developer.mozilla.org/en-US/docs/Web/API/Document/write

Both are depending on timing and might involve race conditions.

Please read this Q/A for further information on SO:

Why is document.write considered a "bad practice"?

Daniel W.
  • 26,503
  • 9
  • 78
  • 128