2

I have this code that I need to convert to async loop since obviously this code for-loop will block the UI/Browser:

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

2 Answers 2

2

Turn your loop into an equivalent recursive function. It then will be easy to use setTimeout when calling itself.

$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));
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.