Here is an example you can learn how to play with timer in JavaScript.
<!doctype html>
<html>
<head>
<title>Timer</title>
<meta charset='utf-8'>
<style>
#viewarea, #controls {
text-align: center;
width: 20em;
}
#viewarea {
background-color: cyan;
}
#sprite {
padding: 10pt;
vertical-align: center;
position: relative;
}
</style>
<script>
var sprite;
var delta;
function setup() {
sprite = document.getElementById('sprite');
}
function moveRight() {
if(delta < 8) {
delta += 1;
} else {
delta = -8;
}
sprite.style.left = delta + 'em';
console.log('delta: ' + delta + ', left: ' + sprite.style.left);
}
function timer() {
moveRight();
if(delta < 8) {
setTimeout(timer, 250);
}
}
</script>
</head>
<body onload='setup();'>
<h1>Timer</h1>
<div id='viewarea'>
<p id='sprite'>@</p>
</div>
<div id='controls'>
<p>
<button onclick='home();'>Home</button>
<button onclick='moveRight();'>Move Right</button><br>
<button onclick='start();'>Start Interval</button>
<button onclick='stop();'>Stop Interval</button><br>
<button onclick='timer();'>Use Timeout</button>
<button onclick='moveFour();'>Move Four</button>
</p>
</div>
</body>
</html>