Background image css animate() within setInterval() function call in JQuery -



Background image css animate() within setInterval() function call in JQuery -

i have noticed behaviour can't explain. i'm sure must limited knowledge of jquery/javascript.

when run next code on webpage, works expected - background image rotates:

//background image rotator var imgarr = new array('/images/1.jpg', '/images/2.jpg', '/images/3.jpg'); var preloadarr = new array(); var i; /* preload images */ (i = 0; < imgarr.length; i++) { preloadarr[i] = new image(); preloadarr[i].src = imgarr[i]; } var currimg = 1; var intid = setinterval(changeimg, 5000); function changeimg() { $('#homediv').css({ 'background': 'url(' + preloadarr[currimg++ % preloadarr.length].src + ')' }); }

however, if replace .css() function .animate(), in next code, currimg++ seems increment 2 , wrong image loads.

//background image rotator var imgarr = new array('/images/1.jpg', '/images/2.jpg', '/images/3.jpg'); var preloadarr = new array(); var i; /* preload images */ (i = 0; < imgarr.length; i++) { preloadarr[i] = new image(); preloadarr[i].src = imgarr[i]; } var currimg = 1; var intid = setinterval(changeimg, 5000); function changeimg() { $('#homediv').animate({ 'background': 'url(' + preloadarr[currimg++ % preloadarr.length].src + ')' }, 1000); }

is due setinterval process getting 'out of sync' due animate() function taking 1000ms?

thanks

alex

remove setinterval , write code

function changeimg() { $('#homediv').delay(5000).animate({ 'background': 'url(' + preloadarr[currimg++ % preloadarr.length].src + ')' }, 1000, function() { changeimg();} ); }

like said, setinterval gets asynchronous animate function. here chaneimg runs 1 time again callback function everytime it's done executing itself.

css jquery

Comments

Popular posts from this blog

delphi - blogger via idHTTP : error 400 bad request -

c++ - compiler errors when initializing EXPECT_CALL with function which has program_options::variables_map as parameter -

How do I check if an insert was successful with MySQLdb in Python? -