Blocking javascript code

Example of long running javascript code

by xufocoder

JavaScript

function delay(ms) {
  const start = Date.now();
  let now = start;
  while (now - start < ms) {
    now = Date.now();
  }
}

function Processor() {
  this.sum = 0;
}

Processor.prototype.calculate = function(i) {
  this.sum += i;
  delay(10);
}

Processor.prototype.result = function() {
  return this.sum;
}

const times = 1000
const processor = new Processor();

for (let i = 1; i < times; i++) {
  processor.calculate(i);
}

console.log(processor.result());