Javascript setInterval works but not infinite loop

为君一笑 提交于 2019-12-02 07:49:29

问题


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>

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/20290885/javascript-setinterval-works-but-not-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!