3

I'm trying to do some heavy calculations in JavaScript. I'm currently using React with Redux.

Doing a fetch or server requests using some library like fetch or jQuery ajax requests are working asynchronous as expected, however I cannot do asynch computations on the client side using my own JavaScript functions.

Doing this inside a React component componentDidMount function using setTimeout like this blocks my UI:

componentDidMount () {
   setTimeout(function() {
      ... do heavy calculations
   }, 0)
}

or inside a dispatch action like this (I'm using redux-thunk):

heavyCalculationsAction: () => {
   return dispatch => {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
           ... perform heavy calculations here
           resolve(data)
        }, 0)
      }).then((data) => {
          distpatch(computationsDone(data))
      })
   }
}

On both cases the UI freezes until the computations are done.

Maybe I should be approaching this with web workers or something else, since I can't get setTimeout to release my UI thread.

Agon Lohaj
  • 33
  • 4

1 Answers1

3

Javascript is single-threaded and generally runs in the UI thread. setTimeout does not run code in a background thread, so anything it runs will block your UI.

To do large amounts of work, you need to use web workers (which run in a separate non-UI thread), or you need to break up your work into smaller chunks, and only do a little bit at a time spread out over time by using setTimeout or requestIdleCallback to schedule each chunk.

Macil
  • 2,916
  • 1
  • 19
  • 17