Asked 7 years ago
14 Jan 2017
Views 3919
shabi

shabi posted

how to Change image automatically in every specified seconds by JavaScript


<script>
var image=['image-1.jpg','image-2.jpg','image-3.jpg'];
var i=0;
function AutoChangeImage(){
document.getElementById('image').src=image[i];
i++;
var d;
for(d=0;d<=2000;d++){
//delay
}

AutoChangeImage();
}

</script>
<img src='image.jpg'  id="image"/>


if you see above code , i made function AutoChangeImage() to change image but i need it should be change image after 2 second and i used for loop to delay it for 2 second

for(d=0;d<=2000;d++){
//delay
}

i am thinking each iteration take one millisecond .
i do not think its good way to use for loop to delay it .not good at JavaScript so suggest something more better

Rasi

Rasi
answered Nov 30 '-1 00:00

yes it is not good to use loop like for or while to make delay in script .

for the delay JavaScript Native have function setTimeout

setTimeout(func , 2000) means run func function after 2 second (2000 milisecond )

so in your case wait for page load complete. window.load is the function will used for it


window.onload=function(){
    setTimeout(function(){
AutoChangeImage();
    }, 2000);
};
Post Answer