Search code examples
javascriptreusabilitycode-readability

JS reduce repeated code


In my JavaScript file, I'm writting a piece of code several times:

setTimeout(function() {
   myFunction("this is a message");
}, 500);

setTimeout(function() {
   myFunction("this is another message");
}, 500);

setTimeout(function() {
   myFunction("this is another message again");
}, 500);
...

So, I want to avoid rewrite the setTimeout all the time.

Is there another way to compact the code and make a better and readable one?

Thanks!

EDIT: My goal is not to launch "myFunction" sequentially. My goal is that when I call myFunction, it always delays 500ms to being executed.


Solution

  • Make a function to wrap the code you're duplicating, and let it take a message as input.

    function delayMessage(msg) {
        return setTimeout(() => {
            myFunction(msg);
        }, 500);
    }
    

    It will return the timeout id in case you need to cancel it with cancelTimeout. Then you can reduce your code to the following:

    delayMessage("this is a message");
    delayMessage("this is another message");
    delayMessage("this is another message again");