I have a setInterval() function saved to a variable in order to able to clear it after with clearInterval().
walkRight = setInterval(moveSnakeRight,1000)
walkLeft = setInterval(moveSnakeLeft, 1000)
walkUp = setInterval(moveSnakeUp, 1000)
walkDown = setInterval(moveSnakeDown, 1000)
//and
clearInterval(walkLeft)
clearInterval(walkRight)
clearInterval(walkUp)
My question is if there is any way to call the same SetInterval again , in this case , walkRight or walkLeft or walkUp. Any of them..
If I try walkRight() it won't work because it is not a function and if I try window.walkRight doesn't work either.
The return value of setInterval is a number that identifies the interval solely for the purposes of clearing it.
There is no way to use that number to get any other information about the interval. You can't use it to determine what function was used to run the interval. You can't use it to call that function again.
If you want that information, you must store it separately.
For example:
const moveSnakeRight = () => {
console.log('moving right');
};
class IntervalController {
constructor(func) {
this.func = func;
this.start();
}
start() {
if (typeof this.interval === "undefined") {
this.interval = setInterval(this.func, 1000);
}
}
stop() {
clearInterval(this.interval);
this.interval = undefined;
}
}
const moveRightController = new IntervalController(moveSnakeRight);
document.querySelector('#start').addEventListener('click', () => moveRightController.start());
document.querySelector('#stop').addEventListener('click', () => moveRightController.stop());
<button id=start>Start</button>
<button id=stop>Stop</button>