Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I currently use setInterval and a wait flag to process this collection. Is there a cleaner way?

var wait = false;
var processInterval = setInterval(function(){
    if(!wait){
        var currentVideo = videos.shift();

        if(currentVideo){
            wait = true;

            validateSongById(currentVideo.videoId, function(result){
                wait = false;
                if(result){
                    clearInterval(processInterval);
                    callback(currentVideo);
                    return;
                }
            });
        }
    }
}, 200);
share|improve this question

1 Answer

up vote 1 down vote accepted

You're basically there, I would say. If the validateSongById function works as expected, it'll call its callback when it's done, and you then do it again for the next video.

function processVideos(videos, callback) {
    var results = [], i = 0;
    function processNext() {
        if(i < videos.length) {
            validateSongById(videos[i].videoId, function (result) {
                results.push(result);
                i++;
                processNext();
            });
        } else {
            callback(results); // when called, all the videos have been processed
        }
    }
    processNext(); // start the processing
}

With this, you call processVideos with the videos array and a callback. The callback is called with a new array of all the results.

Alternatively, you can attach the result to the video-object directly, so the video and the result are tied together:

function processVideos(videos, callback) {
    var i = 0;
    function processNext() {
        if(i < videos.length) {
            validateSongById(videos[i].videoId, function (result) {
                videos[i].result = result;
                i++;
                processNext();
            });
        } else {
            callback(); // when called, all the videos have been processed
        }
    }
    processNext(); // start the processing
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.