Skip to content

Instantly share code, notes, and snippets.

@iiitmahesh
Created August 22, 2017 07:35
Show Gist options
  • Save iiitmahesh/90422777112d2a9dacd26e1017ef6832 to your computer and use it in GitHub Desktop.
Save iiitmahesh/90422777112d2a9dacd26e1017ef6832 to your computer and use it in GitHub Desktop.
doSynchronousLoop in javascript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>doSynchronousLoop</title>
<script type="text/javascript">
function doSynchronousLoop(data, processData, done) {
if (data.length > 0) {
var loop = function(data, i, processData, done) {
processData(data[i], i, function() {
if (++i < data.length) {
setTimeout(function() {
loop(data, i, processData, done);
}, 0);
} else {
done();
}
});
};
loop(data, 0, processData, done);
} else {
done();
}
}
function processData(sum, i, callback) {
console.log(sum, i);
return callback();
}
function done() {
console.log("done");
}
let myArray = [0,1,2]
doSynchronousLoop(myArray, processData, done)
</script>
</head>
<body>
<h1> doSynchronousLoop</h1>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment