javascriptfunctionloopspubnub

How to run an inline-function twice?


I'm using Gametime.js to make a world chat in real time.

Messages are stored in a database.

Gametime.js uses PubNub and for some reason PubNub needs the message sent twice so it actually does it.

How can I make a function run twice?

I've tried this:

for (let i = 0; i < 2; i++) { gametime.run("msg", [msg]) }

And it works, it's just that I do this very often in my script, so is there a way to do it without a for/while loop?

Here's an example of what I'd like to achieve:

// inline code, cannot run for loop right here
function example(msg) { doSomething(), doSomethingElse, {{run twice}}, done() }

Solution

  • You can create another function which will run your function twice, like this:

    function twice (callback) {
      callback();
      callback();
    }
    
    twice(() => console.log('hello'));

    However, if you're experiencing a scenario where you are having to invoke a function twice to get the desired result, it sounds like there's another problem somewhere (in some code that you didn't show).