2

我有这段代码需要转换为异步循环,因为显然这段代码 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)
4

2 回答 2

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));
    });
}
于 2012-10-29T12:13:51.683 回答
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)
于 2012-10-29T12:05:44.117 回答