Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Create New "Thread"

This is a "thread" according to javascript, but the code doesn't seem to fit the conventional threaded model.

Is it possible to make this code clearer, with regards to the concept of a thread?

function test() {     alert("Test"); }  // this creates a new "thread," but doesn't make much sense to the untrained eye setTimeout(test, 0);  

Is there some other way to branch off?

like image 687
skeggse Avatar asked Sep 10 '11 19:09

skeggse


People also ask

How do I start a JavaScript thread?

You start a Thread by calling its start() method with a numeric argument for millis . That will call the Runnable 's run() once every millis milliseconds. (More precisely, it will call run() and then, after run() has finished, it will setTimeout() the next run() after a millis delay.)

Can you make JavaScript multithreaded?

Multithreading in JavaScript is the real right now. You can offload your work into multiple threads and share memory between them.

What are threads in js?

Thread in computer science is the execution of running multiple tasks or programs at the same time. Each unit capable of executing code is called a thread.

How many threads does node actually create?

Using Single thread and Concept of Event Loop: To overcome this problem, Node adopted a single thread system with event loop and asynchronous I/O operations. Using a single thread allows Node to execute one process at a time while the processes that take longer time than usual are handled by Node API and event loop.


1 Answers

You are basically just taking the call to test out of the normal flow and the engine will execute the function whenever it fits, as soon as possible. That means, you are executing test asynchronously.

To make the code clearer, you could create a function with a meaningful name which does the same:

function executeAsync(func) {     setTimeout(func, 0); }  executeAsync(function() {     alert("Test"); }); 

If you want to have real threads, have a look at web workers.

like image 91
Felix Kling Avatar answered Sep 23 '22 13:09

Felix Kling