如何每60秒调用一次JavaScript函数?

Wil*_*iam 1 html javascript recursion html5

所以我正在尝试使用Canvas演示,我希望这个方块从一侧移动到另一侧,但我无法弄清楚如何以每60秒重复一次的方式调用JavaScript.

这是我到目前为止所得到的:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Canvas test</title>
        <meta charset="utf-8" />
        <link href="/bms/style.css" rel="stylesheet" />

        <style>
            body { text-align: center; background-color: #000000;}
            canvas{ background-color: #ffffff;}
        </style>

        <script type="text/javascript">

        var x = 50;
        var y = 250;

        function update(){
            draw();
            x = x + 5;
        }

        function draw(){
          var canvas = document.getElementById('screen1');
          if (canvas.getContext){
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = 'rgb(236,138,68)';
            ctx.fillRect(x,y,24,24); 
            }
        }
        </script>

    </head>

    <body onLoad="setTimeout(update(), 0);">
        <canvas id="screen1" width="500" height="500"></canvas>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

med*_*iev 10

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Canvas test</title>
        <meta charset="utf-8" />
        <link href="/bms/style.css" rel="stylesheet" />

        <style>
            body { text-align: center; background-color: #000000;}
            canvas{ background-color: #ffffff;}
        </style>


    </head>

    <body>
        <canvas id="screen1" width="500" height="500"></canvas> 
        <script type="text/javascript">

        var x = 50;
        var y = 250;

        function update(){
            draw();
            x = x + 5;
        }

        function draw(){
          var canvas = document.getElementById('screen1');
          if (canvas.getContext){
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = 'rgb(236,138,68)';
            ctx.fillRect(x,y,24,24); 
            }
        }
            update();
            setInterval ( update, 60000 );
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

1000ms = 1秒,60000 = 60秒.

  • @William是的.`setInterval("update();",1000);`应该很好用.(注意引号.W/O它们,它是一个更新函数调用.所以,实际上,你将`update`的返回值传递给setTimeout.) (4认同)
  • 正确用于大多数目的.在某些浏览器中,机会可能不会那么准确.我有一段代码每隔*n*秒运行一次函数,它在Internet Explorer中慢慢恶化.如果您需要准确性,请更频繁地运行计时器并手动检查时差. (3认同)