Skip to content

Instantly share code, notes, and snippets.

@tomaszgil
Last active May 12, 2021 18:18
Show Gist options
  • Save tomaszgil/08f8668743b61101dd7f9bac8373cffa to your computer and use it in GitHub Desktop.
Save tomaszgil/08f8668743b61101dd7f9bac8373cffa to your computer and use it in GitHub Desktop.
const startTimestamp = getMiliseconds();
function getMiliseconds() {
return new Date(Date.now()).getMilliseconds();
}
function getMillisecondsElapsed() {
return getMiliseconds() - startTimestamp;
}
function wait(timeout = 0) {
return new Promise((resolve) => setTimeout(resolve, timeout));
}
const tasks = [
() => wait(100).then(() => console.log("Task 1 finished at", getMillisecondsElapsed())),
() => wait(100).then(() => console.log("Task 2 finished at", getMillisecondsElapsed())),
() => wait(100).then(() => console.log("Task 3 finished at", getMillisecondsElapsed())),
];
async function run(tasks = []) {
for (const task of tasks) {
await task();
}
console.log("All tasks finished at", getMillisecondsElapsed());
}
function runForEach(tasks = []) {
tasks.forEach(async (task) => {
await wait(100);
await task();
});
console.log("All tasks finished at", getMillisecondsElapsed());
}
function runLongerForEach(tasks = []) {
tasks.forEach(async (task) => {
await wait(100);
await task();
});
console.log("All tasks finished at", getMillisecondsElapsed());
}
function forEach() {
Array.prototype.forEach = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
}
function patchForEach() {
Array.prototype.forEach = async function (callback) {
for (let i = 0; i < this.length; i++) {
await callback(this[i], i, this);
}
};
}
async function runAsyncForEach(tasks = []) {
patchForEach();
await tasks.forEach(async (task) => {
await task();
});
console.log("All tasks finished at", getMillisecondsElapsed());
}
run(tasks);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment