Revision 62d6bdd1-fb1f-4557-9844-a9b3d4872c85 - Stack Overflow
Although one of the issues described here is a duplicate of http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example, there are other issues like infinite recursive call of `changeBack`.
I think a better approach will be
<!-- begin snippet: js hide: false -->
<!-- language: lang-js -->
/* jshint loopfunc:true */
var url = ["http://protiumdesign.com/wp-content/uploads/2015/04/Material-Design-Background-1024.jpg", "http://i.imgur.com/wt4NRqA.jpg", "http://i0.wp.com/thezinx.com/wp-content/uploads/md-6.png"];
$(document).ready(function() {
var i = 0;
function changeBack() {
$('#elem').fadeTo('slow', 0.3, function() {
$(this).css('background-image', 'url(' + url[i++] + ')');
i = i < url.length ? i : 0
}).fadeTo('slow', 1).delay(1000).promise().done(changeBack);
}
changeBack();
});
<!-- language: lang-css -->
#elem {
width: 500px;
height: 300px;
background-size: 100%;
background-color: red;
}
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='elem'></div>
<!-- end snippet -->