How to work with timer in canvas javascript?

I need to make a rectangle appear randomly somewhere in the canvas, and then it will need to appear randomly in a new place, but I have one problem, it appears a new one but the previous rectangle stay where it was at the beginning and then there are so many rectangles in the canvas, I need to be only one, this is what I’ve done:

 function rectangle(x,y){
    var ctx
    ctx.beginPath();
    ctx.rect(20, 20, 15, 10);
    ctx.stroke();
    }
 function randomMove(){
    var myVar;
    var x;
    var y;
    x = Math.floor(Math.random() * 10) + 1;
    y = Math.floor(Math.random() * 10) + 1;
    myVar = setInterval( ()=> {rectangle(x,y)}, 5000); // pass the rectangle function
    }

Answer

You need to clear the canvas.

The easiest way is to draw a rectangle over entire canvas (assuming it’s a white background)

ctx.fillStyle = "white";
ctx.fillRect(0, 0, width, height);

or if it is transparent…

ctx.clearRect(0, 0, width, height);

You will need to do this on every frame.

const ctx = window.canvas.getContext("2d");

function clearCanvas() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function rectangle(x, y) {
  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.rect(x, y, 15, 10);
  ctx.stroke();
}

function randomMove() {
  var myVar;
  var x;
  var y;
  x = Math.floor(Math.random() * ctx.canvas.width) + 1;
  y = Math.floor(Math.random() * ctx.canvas.height) + 1;
  rectangle(x, y);
}

function draw() {
  clearCanvas();
  randomMove();
}

myVar = setInterval(draw, 200);
draw();
<canvas id="canvas"></canvas>