I would like to measure execution time of a webworker that computes factorization. The webworker is messaging live results and once computations are terminated, the webworker sends a ‘finished’ message. I used promise to do this in my react app.
useEffect(() => {
const measureTimeStart = performance.now();
(async () => {
try {
await new Promise(resolve => {
const worker = new Worker(new URL('facto.js', import.meta.url));
worker.postMessage(number);
worker.onmessage = message => { //streaming live results
const { facto, status } = message.data;
setResults({ ...facto }); //adding them to React state
if (status === 'finished') {
resolve();
worker.terminate();
};
};
});
} catch (error) {
console.log(error)
}
})();
const measureTimeEnd = performance.now();
setExecutionTime(Math.round((measureTimeEnd - measureTimeStart) * 1000) / 1000 + ' ms');
}, [number]); //number to factorize
However, performance.now()
doesn’t wait that the promise resolves and consequently gives me arbitrary timing. Why? thanks.