4

Is javascript running on single thread? If I declare a global array, and start changing it (eg removing elements) on AJAX callback and at the same time start changing the very same array in another function (called with SetTimeOut) - is there a risk of a race condition?

I found this thread: javascript race condition, someone said race conditions never happen in javascript because it always runs in single thread and single callstack. Does this depend on how browser implements it or is it guaranteed to be always single-threaded on all browsers?

Community
  • 1
  • 1
PawelRoman
  • 6,122
  • 5
  • 30
  • 40
  • 2
    There may be race conditions due to network latency if you're working with ajax, but not because of JavaScript itself because it's single-threaded. – pimvdb Mar 15 '12 at 18:45
  • Not quite always: http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded – phazei Mar 28 '13 at 18:42

2 Answers2

4

is it guaranteed to be always single-threaded on all browsers?

Yes.

Of course, things like HTTP requests might work in different threads behind the scenes, but when your Javascript code is executed it can only happen from one thread at a time.

James M
  • 18,506
  • 3
  • 48
  • 56
  • What if I run a script.js file in one tab and in another tab run the same script.js tab, will it still use the same thread? – Phantom007 Jul 30 '21 at 07:03
2

JavaScript is single threaded.

The referenced post discusses differences of setTimeout on different machines...


HTML5 introduces the concept of WebWorkers which executes JavaScript on multiple background threads. Though it is not supported on all browsers...

https://developer.mozilla.org/En/Using_web_workers

http://dev.w3.org/html5/workers/

Alex
  • 34,899
  • 5
  • 77
  • 90
  • With web workers, it's more like having two separate single threaded scripts running and sending messages to each other than having one multithreaded script. A variable can't be visible in both threads, workers can't manipulate the DOM, etc. – James M Mar 15 '12 at 18:55