Goroutines in Squirrel

A **goroutine** is a lightweight thread of execution.

```javascript
function f(from) {
  for (let i = 0; i < 3; i++) {
    console.log(`${from} : ${i}`);
  }
}

function main() {
  f("direct");

  setTimeout(() => f("goroutine"), 0);

  setTimeout(() => {
    console.log("going");
  }, 0);

  setTimeout(() => {
    console.log("done");
  }, 1000);
}

main();

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct");

To invoke this function asynchronously, use setTimeout(() => f(s), 0). This new function invocation will execute concurrently with the calling one.

setTimeout(() => f("goroutine"), 0);

You can also start an asynchronous call for an anonymous function.

setTimeout(() => {
  console.log("going");
}, 0);

Our two function calls are running asynchronously now. Wait for them to finish (for a more robust approach, use a promise or similar mechanism).

To simulate waiting for asynchronous tasks to finish, we use setTimeout.

setTimeout(() => {
  console.log("done");
}, 1000);

When we run this program, we see the output of the blocking call first, then the output of the two asynchronous calls. The output may be interleaved because tasks are being run concurrently by the JavaScript runtime.

Next we’ll look at a complement to asynchronous functions in concurrent JavaScript programs: Promises and async/await.