반응형
setTimer
const Item = class {
time;
block;
constructor(block, time) {
this.block = block;
this.time = performance.now();
}
}
const queue = new Set;
const f = time => {
queue.forEach(item => {
if (item.time > time) return;
queue.delete(item);
item.block();
});
requestAnimationFrame(f);
};
requestAnimationFrame(f);
const timeout = (block, time) => queue.add(new Item(block, time));
timeout(_ => console.log("hello"), 1000);
Non Blocking For
// blocking for
const working = _ =>{};
for (let i = 0; i < 100000; i++) working();
// non-blocking for
const nbFor = (max, load, block) => {
let i = 0;
const f = time => {
let curr = load;
while(curr-- && i < max) {
block();
i++;
}
console.log(i);
if (i < max - 1) timeout(f, 0);
}
timeout(f, 0);
};
nbFor(100, 10, working);
Generator
const gene = function* (max, load, block) => {
let i = 0, curr = load;
while (i < max) {
if (curr--) {
block();
i++;
} else {
curr = load;
console.log(i);
yield;
}
}
};
const nbFor = (max, load, block) => {
const iterator = gene(max, load, block);
const f = _ => iterator.next().done || timeout(f, 0);
timeout(f, 0);
};
nbFor(100, 10, working);
Promise
const gene2 = function* (max, load, block) {
let i = 0;
while (i < max) {
yield new Promise(res => {
let curr = load;
while (curr-- && i < max) {
block();
i++;
}
console.log(i);
timeout(res, 0);
});
}
};
const nbFor = (max, load, block) => {
const iterator = gene2(max, load, block);
const next = ({value, done}) => done || value.then(v => next(iterator.next()));
const next(iterator.next());
};
반응형
'과거' 카테고리의 다른 글
[JS] Lexical Grammar, Language Element (0) | 2021.07.05 |
---|---|
너 왜 코드 그렇게 짰어? (0) | 2021.07.05 |
Runtime Execution, State Control, Flow Control, Sync & Async (0) | 2021.06.17 |
JavaScript - 1 (Version Specifications) (0) | 2021.06.17 |
웹 앱, 자바스크립트 (0) | 2021.06.16 |