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?
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.)
Multithreading in JavaScript is the real right now. You can offload your work into multiple threads and share memory between them.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With