setInterval不起作用(JavaScript) [英] setInterval not working (Javascript)

查看:389
本文介绍了setInterval不起作用(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript中的setInterval定期重绘画布.但是,当我调用setInterval函数时,传递给它的函数仅运行一次.这是我的代码的简化版本:

I'm trying to use setInterval in Javascript to redraw the canvas periodically. However, when I call the setInterval function, the function I pass to it only runs once. Here is a simplified version of my code:

<canvas id="myCanvas" width="400" height="400">
</canvas>
<script type="text/javascript">

function makeBoard()
{
    this.board=[["O", " ", " "], [" ", " ", " "], [" ", "X", " "]];
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ticTacToeBoard=new makeBoard();

var drawCanvas = new Function("printBoard", "");

drawCanvas = function(printBoard)
{
    alert("Calling draw function.");
    // drawing code
}

setInterval(drawCanvas(ticTacToeBoard), 10);
</script>

我已经在Firefox 54.0.1和Google Chrome 59.0版上对此进行了测试.为什么这不起作用,如何获取我的代码以定期重画画布?

I've tested this on Firefox 54.0.1 and on Google Chrome Version 59.0. Why is this not working and how can I get my code to redraw the canvas periodically?

推荐答案

您应该将函数定义传递给setInterval方法,而不是函数调用的结果.

You should pass a function definition to the setInterval method, not the result of a function call.

setInterval(function() {
  // Do something
}, 1000);

对于您的情况,

setInterval(function() {
  drawCanvas(ticTacToeBoard);
}, 10);

这篇关于setInterval不起作用(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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