xxkaiwaxx xxkaiwaxx - 1 year ago 74
Javascript Question

How / When does code in a "For" loop get executed? Javascript

In my example code i'm printing two seperate texts to a Canvas element. Both called to print from inside one function. Inside the function i have a for-loop which, for a specified amount of time, should clear the Canvas and print the first text. Once the for-loop ends it should then print the second text. Then setInterval calls the function again to clear the Canvas completely and print only the first text during the for-loop and the second text at the end of the loop. But the second text prints at the same time as the first text and it is never cleared. So it seems like the code in the for-loop doesn't execute until the for-loop comes to an end. But i also set up console.logs inside and outside the for-loop and the console log inside the for-loop executes in real time, and not at the end of the for-loop. So is it that console.log is a special case in this situation....yet other function calls inside a for-loop must wait till the end before execution? Note: Text won't show till 3 seconds after snippet is run because of the setInterval. Then the snippet page tends to lag, i think, because the for-loop runs for 1.5 secs. Just noticed that now because it wasnt doing that in my text editor.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

function drawText(text, x, y, color, size) {
ctx.font = size + 'px sans-serif';
ctx.fillStyle = color;
ctx.fillText(text, x, y);

function test() {
var beginTime = Date.now();

for (; Date.now() < beginTime + 1500;) {

ctx.clearRect(0, 0, canvas.width, canvas.height);
drawText('Clear canvas and only show this', 100, 100, 'black', '20');

// console.log('for loop ran');

drawText('Dont display this till for-loop stops clearing canvas', 100, 200, 'red', '20');

// console.log('for loop finished');

setInterval(test, 3000);

<canvas id="canvas" width="800" height="600" style="border: 1px solid black"></canvas>

Answer Source

Functions such as clearRect() and setText() are only requests to perform the action as soon as the browser has an opportunity. However, that opportunity doesn't come until after the for loop finishes executing. When the browser finally has a chance to update the canvas, it will process the requests all at once. This means you will only see the final message.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download