2012-10-29 35 views
2

循環我有這樣的代碼,我需要轉換爲異步循環,因爲這顯然代碼迴路會阻止用戶界面/瀏覽器:異步的使用Javascript

$wnd.mainbuff = []; 
    $wnd.update = setInterval(function(){ 
      // fetches everything in the buffer (csv), including old data 
      var temp = $wnd.Recorder.audioData().toString(); 
      var arr = temp.split(','); 
      // so, copy new elements only (must be async) 
      for (var i=$wnd.mainbuff.length; i < arr.length; i++) { 
       console.log(arr[i]); 
       $wnd.mainbuff[i] = arr[i]; 
      } 
     } 
    ,25) 
+0

您是否嘗試使用[web workers](https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers)? – Zeta

+0

看看這裏:http://stackoverflow.com/questions/6998330/how-to-do-threading-in-javascript –

回答

2

將您的循環轉換爲等效的遞歸函數。當調用自己時,它將很容易使用setTimeout

$wnd.mainbuff = []; 
$wmd.curTimerId = null; 
$wnd.update = function() { 
    var start = Date.now(); 
    // fetches everything in the buffer (csv), including old data 
    //        doesn't sound good ^^^^^^^^ 
    var temp = $wnd.Recorder.audioData().toString(); 
    var arr = temp.split(','); 
    // so, copy new elements only 
    function processOne(i, callback) { 
     if (i < arr.length) { 
      console.log(arr[i]); 
      $wnd.mainbuff[i] = arr[i]; 
      setTimeout(function(){processOne(i+1, callback);}, 0); 
     } else 
      callback(); 
    } 
    processOne($wnd.mainbuff.length, function() { 
     setTimeout($wnd.update, 25- (Date.now()-start)); 
    }); 
} 
1

試試這個:

$wnd.mainbuff = []; 
function async(arr, wnd, currentIndex) { 
    console.log(arr[currentIndex]); 
    wnd.mainbuff[currentIndexi] = arr[currentIndexi]; 
} 
$wnd.update = setInterval(function(){ 
     // fetches everything in the buffer (csv), including old data 
     var temp = $wnd.Recorder.audioData().toString(); 
     var arr = temp.split(','); 
     // so, copy new elements only (must be async) 
     for (var i=$wnd.mainbuff.length; i < arr.length; i++) { 
      async(arr, $wnd, i); 
     } 
    } 
,25)