Search code examples
javascriptjquerydelay

How to add delay time into line of code on JavaScript


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


Solution

  • 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);
    });