title: Sieve of Eratosthenes algorithm in JavaScript running endless for large number
body: <p>I have been trying to write <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">Sieve of Eratosthenes</a> algorithm in JavaScript. Basically I just literally followed the steps below:</p>
  
  <ol>
  <li>Create a list of consecutive integers from 2 to (n-1)</li>
  <li>Let first prime number p equal 2</li>
  <li>Starting from p, count up in increments of p and removes each of these numbers (p and multiples of p)</li>
  <li>Go to the next number in the list and repeat 2,3,4</li>
  <li>Add unintentionally deleted prime numbers back to the list</li>
  </ol>
  
  <p>and this is what I have come up with:</p>
  
  <pre><code>function eratosthenes(n){
  var array = [];
  var tmpArray = []; // for containing unintentionally deleted elements like 2,3,5,7,...
  var maxPrimeFactor = 0;
  var upperLimit = Math.sqrt(n);
  var output = [];
  
  // Eratosthenes algorithm to find all primes under n
  
  // Make an array from 2 to (n - 1)
  //used as a base array to delete composite number from
  for(var i = 2; i &lt; n; i++){
      array.push(i);
  }
  
  // Remove multiples of primes starting from 2, 3, 5,...
  for(var i = array[0]; i &lt; upperLimit; i = array[0]){
      removeMultiples: 
      for(var j = i, k = i; j &lt; n; j += i){
          var index = array.indexOf(j);
          if(index === -1)
              continue removeMultiples;
          else
              array.splice(index,1);
      }
      tmpArray.push(k);
  }
  array.unshift(tmpArray);
  return array;
  }
  </code></pre>
  
  <p>It works for small numbers but not for numbers larger than one million. I used Node.js to test and the process just seems endless and no memory error shown up. I've read a solution <a href="https://stackoverflow.com/a/14041122/165820">here</a>(also in javascript) but still cannot fully comprehend it. </p>
  
  <p>Question: How to make this work for sufficiently large numbers such as one million and above?</p>