Javascript setInterval works but not infinite loop

I don't understand why the infinite loop does not work but uncommenting the function call works.

<body>
<canvas id="myCanvas"style="border:2px solid black;" width="1600" height="900">
    Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
    var c = document.getElementById ("myCanvas").getContext ("2d");
    var boxSize = 25;
    var numBoxes = 1;
    var x = 1000;
    var dx = 1;
    var y = 100;
    var dy = 1;
    var a = 0.01;
    var da = 0.1;
    var size = 20;
    var w = c.canvas.width;
    var h = c.canvas.height;

    //function testing () {
    while (true) {
        c.clearRect (0, 0, w, h);
        x = x + 1;
        y = y + 1;
        a = a + 0.1;
        x = x + dx;
        y = y + dy;
        if (x < size / 2 || x + (size / 2) > w) {
            dx = -dx;
            da = -da;
        }
        if (y < size / 2 || y + (size / 2) > h) {
            dy = -dy;
            da = -da;
        }
        c.save ();
        c.translate (x, y);
        c.rotate (a);
        c.strokeRect (-size / 2, -size / 2, size, size);
        c.restore ();
    }

    // testing ();
    // setInterval (testing, 10);
</script>
</body>

Answers:

Answer

When you use setInterval you keep adding the function you are calling to the queue of things for the browser to do. Repaint events are also added to this queue.

When you use an infinite loop, the browser never gets to the end of the function, so it never gets around to running a repaint and the image in the document never updates.

Answer

JavaScript-in-a-browser is a part of a larger construction. You need to align to the rules of this construction and don't hurt it. One of the rule is that your JavaScript must run quick and exit then. Exit means that control gets back to the framework, which does all the job, repaint the screen etc.

Try to hide and show something many times:

for (n = 0; n < 200; n++) {
  $("#test").hide();
  $("#test").show();
}

When this code runs, you won't see any flickering, you will see that the last command will have effect.

Have to say, it's not easy to organize code that way, if you want to make a cycle which paints nice anims on a canvas, you have to do it without while.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.