Allen Huang Allen Huang - 5 months ago 12
Javascript Question

Change background images using setTimeout

I have 31 images and I want to display them one after another as the background of a div. I only want it to change when the user hovers over the div. My problem right now is that it just flips through all the images really fast. I am attempting to use setTimeout, but it isn't working. How can I make the delay work?
The name of the div is About_Me_Block and the images are called frame1.gif,frame2.gif ...etc

Here is my code:

function changeImg(counter) {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
}

$(document).ready(function() {
var hoverAnimate = []
"use strict";
$('#About_Me_Block').mouseenter(function() {
hoverAnimate[0] = true;
var counter = 0;

while (hoverAnimate[0]) {
console.log(counter);
setTimeout(changeImg(counter), 1000);
counter++;
if (counter === 32)
hoverAnimate[0] = false;
}
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate[0] = false;
$(this).attr("style", "background-image: url(play.jpeg);");
});
});

Answer

setTimeout doesn't wait for the function to end, it works lile threading in other languages.

To achieve a what you want, you need to call setTimeout from the changeImg function.

var counter = 0;
$(document).ready(function() {
    var hoverAnimate = []
    "use strict";
    $('#About_Me_Block').mouseenter(function() {
        hoverAnimate[0] = true;
        counter = 0;
        changeImg();
    });
    $('#About_Me_Block').mouseleave(function() {
        hoverAnimate[0] = false;
        $(this).attr("style", "background-image: url(play.jpeg);");
     });
 });

function changeImg() {
    $('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
    counter++;
    if (counter < 32 && hoverAnimate[0]) {
        setTimeout(changeImg, 1000);
    } else {
        hoverAnimate[0] = false;
    }
}