setTimeout in javascript not giving browser 'breathing room'
- by C Bauer
Alright, I thought I had this whole setTimeout thing perfect but I seem to be horribly mistaken.
I'm using excanvas and javascript to draw a map of my home state, however the drawing procedure chokes the browser. Right now I'm forced to pander to IE6 because I'm in a big organisation, which is probably a large part of the slowness.
So what I thought I'd do is build a procedure called distributedDrawPolys (I'm probably using the wrong word there, so don't focus on the word distributed) which basically pops the polygons off of a global array in order to draw 50 of them at a time.
This is the method that pushes the polygons on to the global array and runs the setTimeout:
for (var x = 0; x < polygon.length; x++) {
coordsObject.push(polygon[x]);
fifty++;
if (fifty > 49) {
timeOutID = setTimeout(distributedDrawPolys, 5000);
fifty = 0;
}
}
I put an alert at the end of that method, it runs in practically a second.
The distributed method looks like:
function distributedDrawPolys()
{
if (coordsObject.length > 0) {
for (x = 0; x < 50; x++) { //Only do 50 polygons
var polygon = coordsObject.pop();
var coordinate = polygon.selectNodes("Coordinates/point");
var zip = polygon.selectNodes("ZipCode");
var rating = polygon.selectNodes("Score");
if (zip[0].text.indexOf("HH") == -1) {
var lastOriginCoord = [];
for (var y = 0; y < coordinate.length; y++) {
var point = coordinate[y];
latitude = shiftLat(point.getAttribute("lat"));
longitude = shiftLong(point.getAttribute("long"));
if (y == 0) {
lastOriginCoord[0] = point.getAttribute("long");
lastOriginCoord[1] = point.getAttribute("lat");
}
if (y == 1) {
beginPoly(longitude, latitude);
}
if (y > 0) {
if (translateLongToX(longitude) > 0 && translateLongToX(longitude) < 800 && translateLatToY(latitude) > 0 && translateLatToY(latitude) < 600) {
drawPolyPoint(longitude, latitude);
}
}
}
y = 0;
if (zip[0].text != targetZipCode) {
if (rating[0] != null) {
if (rating[0].text == "Excellent") {
endPoly("rgb(0,153,0)");
}
else if (rating[0].text == "Good") {
endPoly("rgb(153,204,102)");
}
else if (rating[0].text == "Average") {
endPoly("rgb(255,255,153)");
}
}
else { endPoly("rgb(255,255,255)"); }
}
else {
endPoly("rgb(255,0,0)");
}
}
}
}
Ugh I don't know if that is properly formatted, I ended up with an extra bracket <
So I thought the setTimeout method would allow the site to draw the polygons in groups so the users would be able to interact with the page while it was still drawing. What am I doing wrong here?