CharType
CharType

Reputation: 430

setInterval not working (Javascript)

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>

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?

Upvotes: 0

Views: 3205

Answers (1)

nbkhope
nbkhope

Reputation: 7474

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

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

For your case,

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

Upvotes: 3

Related Questions