簡體   English   中英

setTimeout創建一個無限循環

[英]setTimeout creates an infinite loop

我試圖通過更改img標簽的src來隨機地一張一張地顯示不同的圖像。

<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>

但是好像創建了一個無限循環,頁面繼續加載!

傳遞一個函數來調用您的函數,而不是直接調用您的函數。

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

您正在立即調用changeimage ,它立即進行遞歸而不是等待。

通過傳遞一個調用changeimage的函數,它將在調用之前等待5000ms


需要明確的是,我只是替換了上面的錯誤代碼。 其余的應該留在原地。 這是最后一個例子。

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

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

當您從同一個函數中調用一個函數時,它將創建一個循環,如果不停止它,則將是一個無限循環。

問題是您在每個changeimage調用中都在調用changeimage,因此您將面臨循環。

但是您在每個間隔執行一個函數,因此可以使用setInterval

https://developer.mozilla.org/zh-CN/docs/Web/API/Window.setInterval

喜歡:

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"))
}

演示: http//jsfiddle.net/IrvinDominin/Xggb5/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM