I am a relative noob at JavaScript, I have the concepts down but not much execution experience. So there are still many of the scripting language’s subtle nuances which escape me.
Most recently I was experimenting using javascript to scroll the background of an element. nothing fancy ( or tho I am thinking ) just a function global variable, and a function does some counting, changes .style.backgroundPosition, and then uses a settimeout to continue looping.
my script works, but it has a couple of odd quirk which I cannot figure out.
-
it seems the animation goes at different speeds in different browsers. I mean ( and am making the numbers up for the sake of example). it takes maybe 4 seconds for the background to loop completely in Safari, but in FF it only takes 2. is this normal!? does javascript have a different running speed depending on the useragent??
-
The loop has a jerky motion in FF. At first I thought this was a bug in my math or maybe in the way I tiled the background… but I tested it in safari it ran perfectly smooth ( just slower), Which means that the tiling and the # used in scrolling (how hard is it to count from 1 to 600 anyway?) must be fine ( otherwise the “jerk” would have shown up there too).
For such a simple script… are there cross browser differences in the way a loop is executed? does the settimeout run different in different browsers? I guess I would appreciate a more experience coder’s input on this. Comments are much appreicated
JS
var scrll=0;
var scrl_end=600;
var count=0;
function animate(){
scrll++; count++;
scrll2=3*scrll;
document.getElementById(‘ani’).style.backgroundPosition = scrll2+‘px top’;
if (scrll==600){scrll=0;}
setTimeout(“animate()”,10);
}
animate();
CSS
#ani{
border: 3px solid silver;
height:392px; width:580px; margin:0 auto; background-color:#000; padding:10px;
background-image: url(images/moon.gif) repeat-x top left ;
}
HTML
<div id="ani></div>