add alternative fibonacci while loop implementation
[benchmarks-js.git] / busy-wait.js
index 66d58967ed9e86c0cf00b61708379dc46f2e0be4..a851a30e911870542cd9612b2777c7654c057a36 100644 (file)
@@ -8,9 +8,9 @@ const interval = 1000
  * @param timeoutMs
  */
 function dummyTimeoutBusyWait (timeoutMs) {
-  const timeoutTimestampMs = Date.now() + timeoutMs
+  const timeoutTimestampMs = performance.now() + timeoutMs
   // eslint-disable-next-line no-empty
-  do {} while (Date.now() < timeoutTimestampMs)
+  do {} while (performance.now() < timeoutTimestampMs)
 }
 
 /**
@@ -18,10 +18,10 @@ function dummyTimeoutBusyWait (timeoutMs) {
  * @param intervalMs
  */
 async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) {
-  const timeoutTimestampMs = Date.now() + timeoutMs
+  const timeoutTimestampMs = performance.now() + timeoutMs
   do {
     await sleep(intervalMs)
-  } while (Date.now() < timeoutTimestampMs)
+  } while (performance.now() < timeoutTimestampMs)
 }
 
 /**
@@ -45,15 +45,17 @@ async function divideAndConquerTimeoutBusyWait (
  * @param intervalMs
  */
 async function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
-  const tries = Math.round(timeoutMs / intervalMs)
-  let count = 0
-  const triesSetInterval = setInterval(() => {
-    count++
-    if (count === tries) {
-      clearInterval(triesSetInterval)
-      return Promise.resolve()
-    }
-  }, intervalMs)
+  return new Promise(resolve => {
+    const tries = Math.round(timeoutMs / intervalMs)
+    let count = 0
+    const triesSetInterval = setInterval(() => {
+      count++
+      if (count === tries) {
+        clearInterval(triesSetInterval)
+        return resolve()
+      }
+    }, intervalMs)
+  })
 }
 
 Benchmark.suite(
@@ -75,4 +77,6 @@ Benchmark.suite(
   Benchmark.save({ file: 'busy-wait', format: 'json', details: true }),
   Benchmark.save({ file: 'busy-wait', format: 'chart.html', details: true }),
   Benchmark.save({ file: 'busy-wait', format: 'table.html', details: true })
-)
+).catch(err => {
+  console.error(err)
+})