moving a circle with HTML canvas and vanilla JavaScript

Solution 1:

You can do what you want. You have to save the values (the IDs) you get from setInterval calls in order to clear the intervals when you need to. In your code example you are already calling clearInterval but you are passing an undefined value as the parameter. You have to pass the value that you received from a setInterval (or setTimeout) call.

Like this

let posXInt, posYInt;

posUp.onclick = () => {
    clearInterval(posYInt);
    posYInt = setInterval(posUpFunc, 10);
}

posDown.onclick = () => {
    clearInterval(posYInt);
    posYInt = setInterval(posDownFunc, 10);
}

posRight.onclick = () => {
    clearInterval(posXInt);
    posXInt = setInterval(posRightFunc, 10);
}

posLeft.onclick = () => {
    clearInterval(posXInt);
    posXInt = setInterval(posLeftFunc, 10);
}

But if you do that, you will then also need a button to stop the movement of the circle.

// add this button to you layout etc...
stopButton.onclick = () => {
    clearInterval(posXInt);
    clearInterval(posYInt);
}