js實現非同步迴圈實現代碼,js實現非同步代碼

來源:互聯網
上載者:User

js實現非同步迴圈實現代碼,js實現非同步代碼

問題
實現非同步迴圈時,你可能會遇到問題。

讓我們試著寫一個非同步方法呼叫,一次迴圈列印一次迴圈的索引值。

<script>for(var i = 0; i < 5; i++){setTimeout(function(){document.writeln(i);document.writeln("<br />");},1000);}</script>

如上程式的輸出為:

5
5
5
5
5

原因

每次時間結束(timeout)都指向原始的i,而並非它的拷貝。所以,for迴圈使i增長到5,之後timeout運行並調用了當前i的值(也就是5)。

解決方案

有幾個不同的方式可以拷貝i。最普通且常用方法是通過聲明函數來建立一個閉包,並將i傳給此函數。我們這裡使用了自調用函數。

運行代碼

<script>for(var i = 0; i < 5; i++){(function(num){setTimeout(function(){document.writeln(num);document.writeln("<br />");},1000);})(i);}</script>

輸出

0
1
2
3
4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.