When we use JavaScript, we sometimes use the setTimeout function to force code to run late. Such as:

setTimeout(() => { ... The code... }, 0);Copy the code

I hate writing code like this, and I want it to be neat, so we can abstract the setTimeout function as a decorator.

Start by creating a Timeout generation decorator method to simplify our code (TypeScript) :

function  timeout( milliseconds:  number  =  0 ) {

    return  function( target, key, descriptor ) {

        var originalMethod =  descriptor.value;

        descriptor.value  =  function(... args) {setTimeout(() => {

                originalMethod.apply(this, args);

            }, milliseconds);

        };

        returndescriptor; }}Copy the code

Decorator functions in typescript or Babel take three arguments:

target:

It is either a constructor of the class of the decorator function or an instance prototype of the decorator function

key:

The name of the decorated function

descriptor:

All properties of the function being decorated

Here we need to pass in a value as a parameter (0 by default), so we need to use the decorator factory pattern.

The decorator factory pattern is a normal function that returns a decorator function expression at run time.

Next, we take the decorated function and rewrite it to create a new function that wraps around setTimeout.

Ok, I can now use the decorator like this:

class  DemoComponent {

    constructor() {}

    @timeout()
    demoMethod() {// the code here will delay execution} // pass the value @timeout(2000)demoMethod() {// the code here will delay execution}} new DemoComponent().demomethod ();Copy the code

Doesn’t this code look super neat! 😎.

Conclusion:

Decorators are very powerful and can be used not only in various frameworks but also in various libraries, so try them out in your code.

Original text: medium.com/front-end-h…