Reputation: 99
i need a "list" with a number range starting at 0 and ending with around 5 million. I also have to display this within a webbrowser, so i tried javascript and php. Of course, while "loading" all numbers, the browser crashes. Is there a way to prevent that? To actually make it work within a browser? I guess Javascript isnt the right language, but how could i solve this? Help would be appreciated :)
Here is the code so far
function range()
{
var array = [];
var start = (arguments[0] ? arguments[0] : 0);
var end = (arguments[1] ? arguments[1] : 9);
if (start == end) { array.push(start); return array; }
var inc = (arguments[2] ? Math.abs(arguments[2]) : 1);
inc *= (start > end ? -1 : 1);
for (var i = start; (start < end ? i <= end : i >= end) ; i += inc)
array.push(i);
return array;
}
var foo = range(1, 5607249)
for(var i=0;i<foo.length;i++){
document.write(foo[i]);
}
Upvotes: 0
Views: 1266
Reputation: 32511
The only way to display that much data without crashing the browser is to implement some kind of pagination system. Meaning, only show a chunk of your results at a time. You can do this by setting a maximum number of results to show at a time and tracking a page number.
function range()
{
var array = [];
var start = (arguments[0] ? arguments[0] : 0);
var end = (arguments[1] ? arguments[1] : 9);
if (start == end) { array.push(start); return array; }
var inc = (arguments[2] ? Math.abs(arguments[2]) : 1);
inc *= (start > end ? -1 : 1);
for (var i = start; (start < end ? i <= end : i >= end) ; i += inc)
array.push(i);
return array;
}
var foo = range(1, 5607249);
var results = document.querySelector('.results');
var page = 0;
var PAGE_LENGTH = 100;
function showResults() {
var start = page * PAGE_LENGTH;
var end = start + PAGE_LENGTH;
// Write them all at once and put line breaks between them
results.innerHTML = foo.slice(start, end).join('<br />');
}
document.querySelector('.prev').addEventListener('click', function() {
// Make sure we don't go past the first page
page = Math.max(0, page - 1);
showResults();
});
document.querySelector('.next').addEventListener('click', function() {
// Don't go past the end of the results
page = Math.min(page + 1, foo.length / PAGE_LENGTH - 1);
showResults();
});
showResults();
<div class="results"></div>
<button class="prev">Prev</button>
<button class="next">Next</button>
Upvotes: 2