yolandayolanda yolandayolanda - 3 months ago 19
Javascript Question

Can't get JS setInterval to function properly

Trying to wrap my head around the setInterval() method in JS as I am learning JS at the moment. As an exercise I'm trying to generate a lot of flowers (which are just rectangles for now). I thought I could use setInterval() to continuously generate rectangles at different positions, like this:

var c = document.getElementById("primeCanvas");
var ctx = c.getContext("2d");
var xOffset = 10;

function generateFlower(x, y) {
"use strict";
ctx.fillStyle = "#FF0000";
ctx.fillRect(x + xOffset, y, 150, 100);

function addOffset(xPos)
"use strict";

setInterval(addOffset(50), 900);

setInterval(generateFlower(10+xOffset,10), 1000);

However, when I run the script only one rectangle appears in the exact same spot (or possibly more rectangles appear but on top of each other). The intent was for one rectangle to be generated per second adding 50 to the x location of the rectangle (in the HTML canvas).

Can someone see why this does not work?

ton ton

the instruction setInterval(addOffset(50), 900); first executes addOffset(50) then schedule the result to execute in 900ms after that.

I think you want to schedule a job to run addOffset(50) from 900ms after, so you need to do this way:

let intervalId=setInterval(function(){addOffset(50);}, 900);

The intervalId is important to you cancel the schedule job.