raju
raju

Reputation: 129

setTimeout creates an infinite loop

I tried to display different images randomly one by one by changing the src of the img tag.

<img src="dravid-young.jpg" width="350" height="460">
<script type="text/javascript">

var a= new Array ("dravid-childhood.jpg", "dravid-young.jpg", "Jellyfish.jpg", "Tulips.jpg" , "Lighthouse.jpg" , "Penguins.jpg");

$(document).ready(function(){
    var rand = a[Math.floor(Math.random()*a.length)];
    changeimage(a[Math.floor(Math.random()*a.length)]);
});


function changeimage(imag)
{
    $("img").attr("src",imag);
    setTimeout(changeimage(a[Math.floor(Math.random()*a.length)]), 5000);
}

</script>

But it looks like created an infinite loop, the page keep on loading!!

Upvotes: 1

Views: 10286

Answers (3)

user2736012
user2736012

Reputation: 3543

Pass a function that invokes your function instead of invoking your function directly.

setTimeout(function() {
    changeimage(a[Math.floor(Math.random()*a.length)]);
}, 5000);

You were invoking changeimage immediately, which does an immediate recursion instead of waiting.

By passing a function which invokes changeimage, it will wait for 5000ms before invoking it.


To be clear, I was just replacing the erroneous code above. The rest should stay in place. Here's the final example.

function changeimage(imag) {
    $("img").attr("src",imag);

    setTimeout(function() {
        changeimage(a[Math.floor(Math.random()*a.length)]);
    }, 5000);
}

Upvotes: 8

Irvin Dominin
Irvin Dominin

Reputation: 30993

The problem is that you are calling changeimage in each changeimage call so you'll face a loop.

But you are executing a function each interval so you can use a setInterval

https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

Like:

var a = new Array("http://placehold.it/200x200", "http://placehold.it/500x500", "http://placehold.it/300x300", "http://placehold.it/400x400", "http://placehold.it/300x300", "http://placehold.it/200x200");

var intervalID = window.setInterval(changeimage, 1000);

function changeimage() {    
    $("img").prop("src", a[Math.floor(Math.random() * a.length)]);    
    console.log($("img").prop("src"))
}

Demo: http://jsfiddle.net/IrvinDominin/Xggb5/2/

Upvotes: 2

VoronoiPotato
VoronoiPotato

Reputation: 3173

When you call a function from within the same function it creates a loop, and if you don't stop it, it's an infinite loop.

Upvotes: 2

Related Questions