What got you here won't get you there

Non-blocking JavaScript - 1 본문

Web App

Non-blocking JavaScript - 1

optimy 2021. 6. 17. 16:32

병렬성


동시성
동시성
동시성


JavaScript Concurreny


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);

위 코드의 도식화
JavaScript Concurrency의 일부에서 동작


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());
};

'Web App' 카테고리의 다른 글

웹 기초  (0) 2021.09.07
성능 최적화  (0) 2021.09.06
[JS] Object property order  (0) 2021.07.13
JavaScript - 1 (Version Specifications)  (0) 2021.06.17
웹 앱, 자바스크립트  (0) 2021.06.16
Comments