0

im trying to do a function that when user move cursor over image it will show a preview. So im taking the src of the image that fired the event and im changing it into the path of different images.

$('#image').hover(function(){
    var src = "";
    var elem = $(this);
    for (var i=2; i<16; i++) {
        src = elem.attr('src').split('.');
        src[3] = i; 
        src = src.toString();
    src = src.split(',').join('.');
    elem.attr('src', src);
    }
});

The problem is here, when i try to do something like below, putting a delay into every preview it doesn't work as i want.

$('#image').hover(function(){
    var src = "";
    var elem = $(this);
    for (var i=2; i<16; i++) {
        src = elem.attr('src').split('.');
        src[3] = i; 
        src = src.toString();
        src = src.split(',').join('.');
        setTimeout(function() {
            elem.attr('src', src);
        }, 800);
    }
});

How i can solve it? I'm working with that problem for +2h

2 Answers 2

1

The problem is you cant use setTimeout inside a for loop.. Instead of that use setInterval..

 $('#image').hover(function () {
    var src = "";
    var elem = $(this);
    var i = 2;
    var interval = setInterval(function () {
        if (i < 16) {
            src = elem.attr('src').split('.');
            src[3] = i;
            src = src.toString();
            src = src.split(',').join('.');

            elem.attr('src', src);
            i++;
        } else {
            i = 2;
            clearInterval(interval);
        }
    }, 800);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the answer, it worked fine. I was trying a lot of stuff inside the loop and no matter what i've was doing the preview just jump across to the end. So the problem here is that i can't use a delay inside a loop. Really thanks.
0
$('#image').hover(function(){
    var src = "";
    var elem = $(this);
    for (var i=2; i<16; i++) {
        src = elem.attr('src').split('.');
        src[3] = i; 
        src = src.toString();
        src = src.split(',').join('.');

$(elem).delay(800).animate({zoom:1},0,function(){$(this).src(src);});
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.