Skip to content

Instantly share code, notes, and snippets.

@mmocny
Last active July 28, 2023 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmocny/c8ead6eaba1f6f32a8c3de639d360655 to your computer and use it in GitHub Desktop.
Save mmocny/c8ead6eaba1f6f32a8c3de639d360655 to your computer and use it in GitHub Desktop.
processArrayOfWork with PostTask
function processArrayOfWork(arr) {
const item = arr.shift();
console.log(`Processing array item: ${item}`);
if (arr.length > 0) {
// Recursive call.
processArrayOfWork(arr);
} else {
console.log('End processing array of data.');
}
}
function processArrayOfWorkTasky(arr) {
const item = arr.shift();
console.log(`Processing array item: ${item}`);
if (arr.length > 0) {
// Recursive call. Instead of calling directly, postTask so we yield
scheduler.postTask(() => processArrayOfWorkTasky(arr));
} else {
console.log(arguments.callee.name, 'End processing array of data.');
}
}
async function processArrayOfWorkYieldy(arr) {
const item = arr.shift();
console.log(`Processing array item: ${item}`);
if (arr.length > 0) {
// Recursive call. Yield first.
await scheduler.yield();
processArrayOfWorkYieldy(arr);
} else {
console.log('End processing array of data.');
}
}
processArrayOfWork([1,2,3,4,5]);
processArrayOfWorkTasky([1,2,3,4,5]);
processArrayOfWorkYieldy([1,2,3,4,5]);
scheduler.postTask(() => console.log('Running a task posted after the loop'));
scheduler.postTask(() => console.log('Running another task posted after the loop'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment