0

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?

4
  • 3
    You're passing the returned result of calling drawCanvas(ticTacToeBoard) to setInterval() Commented Jul 6, 2017 at 21:18
  • 2
    setInterval(() => drawCanvas(ticTacToeBoard), 10); Commented Jul 6, 2017 at 21:19
  • Your code is basically setInterval(undefined, 10); Commented Jul 6, 2017 at 21:36
  • Ah, I was not aware that setInterval worked that way. It's running fine now, thanks for the explanation. Commented Jul 6, 2017 at 21:47

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.