0
<script>
  var num=10;

  while(num<=20000000){
    document.write(num+'<br/>');
    num++;
  }
</script>

As you can see above num starts at 10 and goes till 20 million. But, this program does not work on my computer. My computer just freezes after running this code for few seconds. Does 20 million is very big value which javascript can't handle or their is issue with browser memory about which I am unaware. If I run same logic in c , it does work. What's the problem here?

My computer configuration : 

Main Memory : 2GB

processor : Intel Quad core processor ( up to 2.66 GHz)
3
  • Viewer cannot read twenty million lines in document at once. Using while loop is not necessary. Append #text nodes to document incrementally. Commented Feb 18, 2017 at 6:55
  • Modifying the DOM is expensive. You can have better luck concatening the string and adding it at once (or each million, perhaps). Commented Feb 18, 2017 at 7:00
  • See jQuery - Can threads/asynchronous be done? process 10,000 items 250 items at a time; How to solve Uncaught RangeError when download large size json process download of 189.8 MB (189,778,220 bytes) file Commented Feb 18, 2017 at 7:16

1 Answer 1

2

The real bottleneck here would the browser rendering. Don't forget that you are adding a huge amount of data to the DOM that all has to be handled.

If you just want to try out loops and play around in Javascript, maybe the better choice would be to use NodeJS where you can run your program outside of the browser environment

var timerLabel = 'running_loop';
function loop() {
  var num = 5;
  while (++num < 20000000) {
  }
}

// starts a timer
console.time(timerLabel);
loop();
// marks in ms how long the operation took
console.timeEnd(timerLabel);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.