DEV Community

artydev
artydev

Posted on

Poor man's decorator in Javascript

If you miss decorators in Javascript, you can use 'bind' to achieve it.

Here is a very simple way illustring how to defer and trace the execution of a function:

DecoJS:

function sleep(ms) {
  return new Promise((res) => {
    setTimeout(res, ms)
  })
}

async function deferExec(ms) {
  console.log("start : ", (new Date()).toLocaleTimeString());
  await sleep(ms)
  this()
  console.log("end : ", (new Date()).toLocaleTimeString())
}

let counter = 0

const incCounter = () => {
  for (var i = 0; i < 1000; i++) {
    counter += i
  }
}

deferExec.bind(incCounter)(1000)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)