Search code examples
javascriptjqueryasynchronousjavascript-objectsdom-events

setTimeout vs normal function execution in Javascript


In my application, I have a submitSuccesscallback function, which will be triggered from my own JS library when submit was successful. Within submitSuccesscallback, I am first displaying a loader and doing some initialization operations.

function submitSuccesscallback(){
  showLoadingIndicator(); // has code a display loader
  doSubmitSuccessOperations();// has code to do some app specific operations
}

here doSubmitSuccessOperations() is taking around 5 secs for complete execution.

Now my problem is above code does n't display loader (i.e ui changes from showLoadingIndicator()) upto 5 secs after I get the submitSuccesscallback().

If I change submitSuccesscallback() like below, I am able to see loader immediately after I trigger submitSuccesscallback().

 function submitSuccesscallback(){
  showLoadingIndicator(); // has code a display loader
  setTimeout(doSubmitSuccessOperations, 1000);
}

Now what I would like to know is:

  1. does setTimeout makes my doSubmitSuccessOperations() run in background?

  2. I clearly sense that doSubmitSuccessOperations() is blocking UI operation, is there any concept of UI thread and background thread in JS?

  3. Any other alternative for setTimeout above?


Solution

  • does setTimeout makes my doSubmitSuccessOperations() run in background?

    No. JS is single-threaded. Code and rendering are in the same thread. That's why long-running operations block rendering.

    What setTimeout does is set aside that operation until the engine can execute it (it doesn't halt running code) and is at least (and not exactly) after the delay you specified. Code that comes after it executes normally as if it were the next operation in the thread. That means the code inside setTimeout is already not in the same order it appears in your code.

    I clearly sense that doSubmitSuccessOperations() is blocking UI operation, is there any concept of UI thread and background thread in JS?

    Any other alternative for setTimeout above?

    Async programming is one, and timers (setTimeout and friends) are the most available. In other environments, IE has setImmediate, and Node has process.nextTick. There's also WebWorkers, which are closer to real threads. If you have a server, you can use AJAX (which is also a form of async operation) to call a server and let it do the operation for you.

    Here's a video that explains how the event loop works. Somewhere in the middle of the video explains how setTimeout schedules your callbacks.