Javascript setInterval工作但不是无限循环 [英] Javascript setInterval works but not infinite loop

查看:132
本文介绍了Javascript setInterval工作但不是无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么无限循环不起作用,但取消注释函数调用的作用。

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>


推荐答案

JavaScript在浏览器中是一个较大的建筑。你需要符合这个建设的规则,不要伤害它。其中一个规则是您的JavaScript 必须快速运行,然后退出。退出意味着控制回到框架,它完成所有的工作,重绘屏幕等。

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.

尝试隐藏和显示多次:

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.

这篇关于Javascript setInterval工作但不是无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆