【问题标题】:Asynchronous for loop with Javascript使用 Javascript 的异步 for 循环
【发布时间】:2012-10-29 11:50:28
【问题描述】:

我有这段代码需要转换为异步循环,因为显然这段代码 for-loop 会阻塞 UI/浏览器:

    $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)

【问题讨论】:

标签: javascript


【解决方案1】:

把你的循环变成一个等效的递归函数。然后在调用自身时使用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));
    });
}

【讨论】:

    【解决方案2】:

    试试这个:

    $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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多