Javascript setTimeout(0),閉包

來源:互聯網
上載者:User

標籤:cti   函數   ack   time   script   class   nbsp   str   ret   

setTimeout常常被用於延遲運行某個函數,使用方法為

setTimeout(function(){

…

}, timeout);

  

有時為了進行非同步處理,而使用setTimeout(function…,0);比方

function f(){

… // get ready

setTimeout(function(){

…. // do something

}, 0);

  

return …;

}

  

在setTimeout設定的函數處理器之前,函數f返回;

  

在使用非同步處理時。尤其是使用閉包特性時。要特別小心;比如

for(var i = 0 ; i < 10; i++){

setTimeout(function(){

console.log(i);

}, 0);

}

  

對於初次使用這樣的方式的同學來說。非常可能會覺得程式會列印0…9。可結果確實列印10個10;

  

問題就在於,當迴圈完畢時,function得到運行,而i已經變成10,console.log(i)中使用的是10!

  

增加你的目的是列印0…9,那麼能夠換一種方式,用函數參數來儲存0….9(事實上也是利用了閉包)

for(var i = 0 ; i < 10; i++){

setTimeout((function(i){

return function(){

console.log(i);

}

})(i), 0);

}

Javascript setTimeout(0),閉包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.