I have a problem with my site, or at least I think I have. I use a very simple nearly recursive Javascript function to move two pictures. However, on my four year old computer, this is not a smooth movement. I’ve reduced the size of the pictures, but…
The code is not recursive as I use setTimeout between calls.
The code is the following:
(onload)
sImgArray = ["imgLaVera", "imgAlmanzor", "imgRosarito", "imgBaile"];
iImg = sImgArray.length - 1;
setTimeout('playShow(0,' + iImg + ')', 4000);
function playShow(iVisible, iImgs)
{
if( iVisible < iImgs )
iLeft = iVisible + 1;
else
iLeft = 0;
imgLeft = document.getElementById(sImgArray[iLeft]);
imgLeft.style.left = "-" + imgLeft.width + "px";
playMove(-imgLeft.width, iVisible, iImgs);
}
function playMove(i, iVisible, iImgs)
{
if( iVisible < iImgs )
iLeft = iVisible + 1;
else
iLeft = 0;
imgLeft = document.getElementById(sImgArray[iLeft]);
imgRight = document.getElementById(sImgArray[iVisible]);
if( i < 0 )
{
i = i + 5;
imgLeft.style.left = (i - 2) + "px";
imgRight.style.left = (i + imgLeft.width) + "px";
setTimeout('playMove(' + i + ', ' + iVisible + ',' + iImgs + ')', 75);
}
else
{
if( iVisible < iImgs )
iVisible = iVisible + 1;
else
iVisible = 0;
setTimeout('playShow(' + iVisible + ',' + iImgs + ')', 4000)
}
}
Any suggestions?
The following settings in
playMovewill give you what you want:Your animation seemes sluggish because you’re changing image positions rarely and with big jumps. If you want it to be smoother you should change the positions more frequently but less pixels in each step.
Sidenotes
If you really care for speed, don’t select elements in every call of the rendering function (
playMove).Do this at the end of
showbefore callingsetTimeout:Now you can simply write
instead of
in playMove and playShow.
Secondly you should try to avoid passing functions as textual parameters because they need to be evaled separately.
Thirdly this is like the ugliest thing I’ve seen in my life:
Don’t use the
thisreference to pass parameter to a function. That’s what normal parameterlist is for.Then your function
showbecomes something like this: