0

I was wondering how can I start, join and detach threads in JS.

I saw information about Service Workers, which are meant to run as separate processes in the background, not exactly what I'm looking for. Is there something else? How can I use it?

4
  • 1
    JavaScript (in the common engines) is single threaded. So if you need to distribute tasks among different CPUs then you need to use workers or child processes. Commented Oct 22, 2018 at 10:54
  • @t.niese - No, JavaScript isn't single-threaded. Most environments run a single thread per global environment (sometimes sharing that thread across more than one global environment), which is different from the language being single-threaded. Commented Oct 22, 2018 at 10:55
  • @Archer I think possibility of serial up voting? +1 on your comment Commented Oct 22, 2018 at 11:00
  • Maybe this helps explaining the event loop. Some methods like fetch will run asynchronously in their own thread and return a promise. Commented Oct 22, 2018 at 11:31

2 Answers 2

1

You probably don't want service workers, but rather web workers (spec | MDN article) on browsers or worker threads on Node.js.

Sign up to request clarification or add additional context in comments.

1 Comment

I will look into it, probably was on the wrong path, thanks
0

JavaScript in the main window runs on a single thread, it can run asynchronous functions that will turn to progress in the same thread. See:

This two APIs will allow you to run different threads:

Web Workers https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API (run and die kind of script thread execution) example:

var myWorker = new Worker('worker.js');
myWorker.postMessage('Message posted to worker');

Service Workers https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API (run in the background between the network and the application)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.