How to change background on every 5s

Here is an example (that does not need jQuery to work) :

var rotate = false;
function setbackground(){
  window.setTimeout( "setbackground()", 5000);
  newImage = rotate ? 'url(pict1.jpg)' : 'url(pict2.jpg)';
  rotate = !rotate;
  document.getElementById('change').style.backgroundImage = newImage;
}

Use setInterval and setTimeout

window.setInterval(function(){    
   window.setTimeout(function(){
       $('div').css('background-image','url(background.jpg)');
   },100);
    $('div').css('background-image','url(background_n.jpg)');
},10000);

example: http://jsfiddle.net/niklasvh/M56A6/


  • You can use setTimeout(function, timeout) (plain Javascript function) to set a function (which you can define) to run after timeout milliseconds

    For example (the alert will be displayed after 10 seconds):

    setTimeout(function () {
         alert('I am running!');
    }, 10000);
    
  • You can change an element's background with:

    $(element).css('background-image', 'url(xy.jpg)')
    
  • Make sure you preload you background images before using them.

  • I'd advise against using setInterval() for this (for such small intervals, it could stack up), use a chain of setTimeout()s to set up the repeating action.