Помогите с функциями паузы в игре змейка
Создал простую игру змейка на JavaScript и столкнулся с проблемой. Нужно добавить возможность ставить игру на паузу и продолжать её при нажатии на кнопки.
Вот заготовки функций, которые пока пустые:
function stopGame(){
// что тут должно быть?
}
function continueGame(){
// и тут тоже не знаю
}
const pauseBtn = document.getElementById('stop').addEventListener('click', stopGame)
const playBtn = document.getElementById('start').addEventListener('click', continueGame)
А это основной цикл игры:
function mainLoop(){
currentPos.x += direction.x
currentPos.y += direction.y
// когда змея съедает еду
if (food.x == currentPos.x && food.y == currentPos.y) {
tail.push({...currentPos})
currentPos.x += direction.x
currentPos.y += direction.y
generateFood()
points++
}
// проверка столкновения с телом
if (direction.x || direction.y) {
for (let segment of tail) {
if(segment.x == currentPos.x && segment.y == currentPos.y){
return restart()
}
}
tail.push({...currentPos})
tail.shift()
}
updateScore(points)
// телепорт через стены
if (currentPos.x < 0){
currentPos.x = GRID_SIZE
}
else if (currentPos.y < 0){
currentPos.y = GRID_SIZE
}
else if (currentPos.x > GRID_SIZE){
currentPos.x = -1
}
else if (currentPos.y > GRID_SIZE){
currentPos.y = -1
}
}
setInterval(function(){
requestAnimationFrame(mainLoop)
}, SPEED)
Как правильно организовать паузу в такой структуре кода?