Timing Functions in JavaScript


Uncategorized

Updated Aug 6th, 2023

Goal: Create a wrapper for a function that can time how long the function takes to execute.

In Python (for a Classes’ Methods in TS) you would reach for decorators. But to accomplish this for any function in JS you would use higher order functions and closures.

Here is an implementation:

// Reusable timing function with execution time measurement
function timingFunction(fn) {
  return function (...args) {
    return new Promise(resolve => {
      const start = performance.now()
      console.log("Stopwatch started for the " + fn.name + " function")
      const result = fn.apply(this, args)
      if (result instanceof Promise) {
        result.then(() => {
          const end = performance.now()
          const executionTime = end - start
          console.log(`The ${fn.name} function took ${executionTime} milliseconds to execute.`)
          resolve()
        })
      } else {
        const end = performance.now()
        const executionTime = end - start
        console.log(`The ${fn.name} function took ${executionTime} milliseconds to execute.`)
        resolve()
      }
    })
  }
}

// Example function to apply timing function and measure execution time
function sayHello(name) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(`Hello, ${name}!`)
      resolve()
    }, 7000) // X seconds delay
  })
}

// Applying the timing function to the sayHello function
const timedSayHello = timingFunction(sayHello)

// Calling the delayedSayHello function
timedSayHello("John").then(() => {
  console.log("Full execution completed")
})

A few things to note include:

It needs to handle the returning of promises so it waits for things like “setTimeouts” as you would expect.