2013-04-01 58 views
0

我無法將頭圍繞在這個之上?
爲什麼它是我的:
.each循環運行正常,即使我在每個循環1000毫秒內拖延?
問題是,window.location.href命令運行到setTimeout的之前早完成?同樣的stopload()函數也會提前結束?我已經看到了關於遞歸setTimeout函數的一些東西,這裏需要什麼以及如何實現?防止JS代碼在功能結束之前運行

function shop(clickedButton) 
{ 
    var buttonvalue = $(clickedButton).val(); 
    startLoad(); 
    pdel = 1000; 

    $("input:submit[value='buy']").each(function(index) 
    { 
    if(index != 1) 
    { 

     $("#backgroundPopup").text(index); 
     var submithing = this; 
     setTimeout(function(){ clicksubmitbutton(submithing); },pdel); 
     pdel += 1000; 
    }      
    }); 

    stopLoad(); 

    if(buttonvalue == "1") 
    { 
    window.scrollTo(0,0); 
    } 
    else 
    { 
    window.location.href = 'http://my.url'; 
    }      

}

+2

'setTimeout'不熄火什麼。你只是告訴JavaScript在未來執行某些事情,*當前腳本執行終止後。如果您想在超時後執行某些操作,則必須從超時中將其放入/呼叫。 –

回答

2

JavaScript有沒有睡眠,或失速的概念。繼續執行setTimeout呼叫。這個函數簡單地安排一個函數在給定的毫秒數之後運行。

爲了獲得您想要的行爲,您需要調用setTimeout回調函數中的下一次迭代。

喜歡的東西:

function submitTheThing(index) { 
    if (done) { //some logic 
     return; 
    } 

    // do something 

    setTimeout(function() { submitTheThing(index+1); }, 1000); 
} 
相關問題