Zenneson Zenneson - 29 days ago 5
HTML Question

Changing src after 3 seconds

I am trying to change the src attribute of an image with the class of "bg" after 3 seconds on a loop. It goes from "bg1.jpg" to "bg5.jpg". For some reason my code is not working and I am not getting any errors.

$(document).ready(function(){

var $bg = $('.bg');

function bgChange() {
var i = 1;
while ( i < 6 ) {
var background = '<?php echo $siteroot; ?>/img/bg' + i + '.jpg';
setTimeout($bg.attr('src', background), 1000);
i++;
if ( i === 5 ) {
i = 1;
}
}
}

bgChange();
//------------------------------------
});

Answer

You should change src one by one with interval time so don't use while || for loops.

Try this example with setTimeout()

var $bg = $('.bg');

function bgChange(i) {
  if(i == 6)i = 1; // reset
  var background = '<?php echo $siteroot; ?>/img/bg' + i + '.jpg';
  $bg.attr('src', background); // change src
  setTimeout(function(){bgChange(i++)}, 3000); // call again after 3 sec
}

bgChange(1);
Comments