2012-10-29 34 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)