Search code examples
javascripthtmltiming

How do I delay this code running in JavaScript?


I have written this code to change an image:

change = function(){
    for (r=0; r<6; r++){
        for (i = 0; i < 6 ; i++) { 
            setInterval(imgfile(number=i+1), 5000);
        }
    }
}

imgfile= function(number){
    a = 'document.getElementById("imgdiv").src = "images/'+number+'.svg"';
    eval(a);
}

The function change() is called when a button is clicked. When I press the button the image changes straight to 6.svg, when I want it to go through the images 1, 2, 3, 4, 5, 6 and to repeat it 6 times. When I change setInterval to change.setInterval or imgfile.setInterval it doesn't work at all. How do I fix this?


Solution

  • change = function(i=0){
            imgfile(i%6+1);//change image
             if(i<36) setTimeout(change,5000,i+1);//next image in 5 seconds
    }
    
    imgfile= function(number){
        document.getElementById("imgdiv").src = "images/"+number+".svg";//no need to use ev(i||a)l
    }
    

    Instead of loop/interval mess you can simply start a timeout that restarts itself after changing the image... This code will loop over 6 images with a delay of 5 seconds and that 6 times...