Skip to content

Instantly share code, notes, and snippets.

@1eedaegon
Last active July 11, 2021 14:26
Show Gist options
  • Save 1eedaegon/8ba85c1d91134d2d854cff043a1b6ac7 to your computer and use it in GitHub Desktop.
Save 1eedaegon/8ba85c1d91134d2d854cff043a1b6ac7 to your computer and use it in GitHub Desktop.
Concept: Dynamic time division flow control
// Typically, mordern client systems limit it 60 milliseconds
const FRAME_LIMIT = 100 // milliseconds, naaive
const TDFC = (MAXROW, cb) => {
return new Promise(resolve => {
const maxRow = MAXROW;
let cursor = 1; // start point
let partialMax = 10; // minimal loop block
let before = new Date().getTime();
let result;
const loop = () => {
for (; cursor <= partialMax && cursor <= maxRow; cursor += 1) {
result += cb(cursor); // Sometimes it can be an addition or append operation
}
if (cursor < maxRow) {
const after = new Date().getTime();
const timeDiff = after - before || 1;
const perMillisec = timeDiff / partialMax;
partialMax = parseInt(FRAME_LIMIT / perMillisec, 10) + cursor;
before = after;
setTimeout(loop, FRAME_LIMIT);
} else {
resolve(result);
}
};
loop();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment