35

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?

1
  • But the execution of the test function will be on the main thread, so if your test has some heavy code, your server or app will hang. The timekeeping of the timeout only happens asynchronously. I think workes would be most closely in terms of thread.
    – Epsi95
    May 27, 2021 at 6:44

1 Answer 1

45

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.

3
  • 1
    I just need to run asynchronously, threads aren't necessary. Thanks!
    – skeggse
    Sep 10, 2011 at 19:32
  • 3
    Web workers arn't an option for most web applications (see link) Basically, IE 10 is the first version to support it. caniuse.com/webworkers May 23, 2013 at 15:37
  • 7
    A lot has changed since @komma8.komma1's comment. Now you can use web workers in almost all browsers! Jun 1, 2017 at 20:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.