I have a script that draws a bunch of lines on canvas, but it’s pretty intense so while rendering freezes browser for a few seconds. I added setTimeout() so that the browser wouldn’t freeze and it effectively messed up my script. It’s difficult to explain how, so I have two examples online:
Without setTimeout() : http://www.modwebsolutions.com/test1
With setTimeout() : http://www.modwebsolutions.com/test2
Note, that I only change a single line in the whole script, that is line 69:
without setTimeout(): vLoop();
with setTimeout(): setTimeout(vLoop,1);
The problem here, as hinted at by others, is that you are drawing the lines a quadrant at a time. As soon as the
SetTimeoutmethod is called and the firstvLoopreturns, the code carries on running into the nextdrawVerticalwhich changes all the global variables and so on.What you need to do is synchronise how you’re calling vLoop and how you are changing the globals.
This is basically the solution:
Replace …
… with …
Replace your
drawVerticalfunction with …change the
vLoopfunction prototype to look like this …and finally replace your recursive
vLoopcall (from within vLoop) with …The last block is where it ensures that the quadrants are not stepping over each other.