I'm trying to write a function to slowly move an image around the screen. The relevant html is as follows:
var dom, timer;
function initImage() {
dom = document.getElementById('animate').style;
dom.position = 'absolute';
dom.top = "165px";
dom.left = "767px";
regulate(1115,165);
regulate(1115,540);
regulate(767,540);
regulate(767, 165);
}
function regulate(xfinal, yfinal) {
var timer = setInterval(function() {moveImage(xfinal,yfinal)}, 1);
return true;
}
function moveImage(xfinal, yfinal) {
var x = parseInt(dom.left.match(/\d+/));
var y = parseInt(dom.top.match(/\d+/));
if ((x == xfinal) && (y== yfinal)) {clearInterval(timer);}
else {
if (x != xfinal) {
if (x < xfinal) {x++;}
else {x--;};
dom.left = x + "px";}
else {
if (y < yfinal) {y++;}
else {y--;};
dom.top = y + "px";};
};
return true;
}
<img src='http://placehold.it/200' alt='Sir Victor' width=50 height=50
id='animate' onload='initImage();' style='position:absolute;'/>
This algorithm works fine for the first function call to regulate(), but when I uncomment one of the other three and try to run it, the image either doesn't move at all, or it moves faster than normal, but only along the first path. Is there some reason the function won't act as expected the second time?
I'm new to javascript, so feel free to point out anything else that seems dumb or over-complicated as well.
timerwithin the global scope as well (given you're referencing it in bothmoveImageandregulate. (May not be THE issue, but it's at least AN issue.