I'm trying to make snake game in js and i have this movement code, where sq is moving DIV:
window.onkeyup = function move(e)
{
switch(e.keyCode)
{
case 37:
function moveLeft()
{
sq.style.left = parseInt(sq.style.left) - 20 + 'px';
checkGameOver();
}
setInterval(moveLeft, 500);
break;
case 38:
function moveUp()
{
sq.style.top = parseInt(sq.style.top) - 20 + 'px';
checkGameOver();
}
setInterval(moveUp, 500);
break;
case 39:
function moveRight()
{
sq.style.left = parseInt(sq.style.left) + 20 + 'px';
checkGameOver();
clearTimeout(timeLeft);
}
setInterval(moveRight, 500);
break;
case 40:
function moveDown()
{
sq.style.top = parseInt(sq.style.top) + 20 + 'px';
checkGameOver();
}
setInterval(moveDown, 500);
break;
}
}
But any time i change move direction, last direction stays and movement is not correct. The question is how can i make correct movement and also how to stop a div?