Tuesday, October 4
Shadow

make a loop non-blocking with await new promise that resolves after a timeout

// 28 aug 2022
// blocking vs awaiting
// make a loop non-blocking with await new promise that resolves after a timeout

function block(ms, pause) {
  return (async function (end) {
    end = ms + performance.now();
    var ticks = 0;
    while(performance.now() < end) {
      pause && (await new Promise(res => setTimeout(res, 0)));
      ticks = 1 + ticks;
    }
    console.log({ ticks, pause });
    return end;
  })();
}

console.log("** one **");

block(1000).then((v) => {
  console.log("done");
  console.warn(v)
});

console.log("** two **");

block(1000, true).then((v) => {
  console.log("done");
  console.warn(v)
});

console.log("** end **");

/*
** one **
Object { ticks: 2152484, pause: undefined }
** two **
** end **
done
1284703
undefined
Object { ticks: 65, pause: true }
done
1285704
*/

Leave a Reply