ysfaran
ysfaran

Reputation: 7022

Does it make sense to execute functions in event handlers async?

Let's say there is a function which is doing some complex/long running stuff:

const somethingMoreComplexSync = value => {
  let stupidString = value;
  for (let i = 0; i < 100000000; i++) {
    stupidString = i % 2 === 0 ? stupidString + "1" : stupidString.slice(0, -1);
  }
  return stupidString;
};

(This function is actually just returns value which was passed as parameter)

Now imagine you want to call this function once you type something in a input field:

const MyComponentSync = () => {
  const handleChange = e => {
    const complexValue = somethingMoreComplexSync(e.target.value);
    console.log(complexValue);
  };

  return (
    <label>
      Sync
      <input onChange={handleChange} />
    </label>
  );
};

So each time you type a character onChange will be triggered, thus somethingMoreComplexSync will be triggered.

This question here is: Does it make any sense to make somethingMoreComplexSync async?

As far as I can imagine events are called async anyway? (Is this true?)

See this codesandbox which also contains an async implementation of the above.

Upvotes: 0

Views: 53

Answers (1)

Quentin
Quentin

Reputation: 943769

Does it make sense to execute functions in event handlers async?

Being in an event handler is no reason to make code asynchronous.

Let's say there is a function which is doing some complex/long running stuff

Then it may well be sensible to farm the work it is doing out to a Web Worker or similar to take the load off the main event loop … because it is long running not because it has anything to do with events.

See this codesandbox which also contains an async implementation of the above.

There's nothing asynchronous about that. It's wrapped in promises (which are tools to manage asynchronous code), but it is still blocking.

Upvotes: 1

Related Questions