0

In the for loop i'm iterating through the array of strings and meanwhile changing the src of image but, setTimeout method is not holding myfun for 3000 ms because of this the for loop just iterate in a blink of any eye to the last string of array. Where I'm going wrong?

<script>
 function myfunction(){
 var arr = ["mind.jpg","images.jpg","external.jpg"];
 var image = document.getElementById("IMAGE");

 for(var i =0;i<arr.length;i++)
 {
    setTimeout(myfun,3000);      
    image.src = arr[i];

 }
 }   
 function myfun(){

 }
</script>
Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
Ria
  • 1
  • 2
  • 2
    This is the intended (and most usefull) bevahiour of `setTimeout` - it puts some function to event loop and continue running, making it possible to run functions asyncronically. – Nikolai Mavrenkov Apr 13 '16 at 18:11
  • It's `setTimeout`, an asynchronous method, not a `sleep` method that blocks everything. – Bergi Apr 13 '16 at 18:14
  • `setTimeout` executes the callback after the delay (in your case the callback is `myfun`. If you want to set `image.src` on a delay, you should do it from within the callback, however you will also need to use a closure to capture the value of `i` – Damon Apr 13 '16 at 18:16

2 Answers2

1

If you want to make something like slideshow, you need to do it like this:

function myfunction() {
    var arr = ["mind.jpg","images.jpg","external.jpg"];
    var image = document.getElementById("IMAGE");
    var i = 0;
    function next() {
        image.src = arr[i];
        if(++i === arr.length) {
            i = 0
        }
    }
    setInterval(next, 3000)
}
Nikolai Mavrenkov
  • 1,851
  • 18
  • 21
0
for (var i = 0; i < arr.length; i++) {
    myfun(i);
}

function myfun(i) {
    setTimeout(function() {
        image.src = arr[i];
    }, 3000 * i);
}

for (var i = 0; i < 5; i++) {
    myfun(i);
}

function myfun(i) {
    setTimeout(function() {
        document.write(i + '<br>');
    }, 1000 * i);
}
isvforall
  • 8,768
  • 6
  • 35
  • 50