Timeouts in JavaScript

Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in JavaScript is straightforward using Promises and setTimeout.

const main = async () => {
    // For our example, suppose we're executing an external
    // call that returns its result as a Promise that resolves
    // after 2s. This is a common pattern for asynchronous operations.
    const operation1 = () => new Promise(resolve => {
        setTimeout(() => resolve("result 1"), 2000);
    });

    // Here's the Promise.race implementing a timeout.
    // We create a timeout promise that rejects after 1 second,
    // and race it against our operation.
    try {
        const result = await Promise.race([
            operation1(),
            new Promise((_, reject) => setTimeout(() => reject(new Error("timeout 1")), 1000))
        ]);
        console.log(result);
    } catch (error) {
        console.log(error.message);
    }

    // If we allow a longer timeout of 3s, then the operation
    // will succeed and we'll print the result.
    const operation2 = () => new Promise(resolve => {
        setTimeout(() => resolve("result 2"), 2000);
    });

    try {
        const result = await Promise.race([
            operation2(),
            new Promise((_, reject) => setTimeout(() => reject(new Error("timeout 2")), 3000))
        ]);
        console.log(result);
    } catch (error) {
        console.log(error.message);
    }
};

main();

Running this program shows the first operation timing out and the second succeeding.

$ node timeouts.js
timeout 1
result 2

In this JavaScript version, we use Promises and async/await to handle asynchronous operations. The Promise.race method is used to implement the timeout mechanism, racing the actual operation against a timeout Promise. If the timeout Promise resolves first, it throws an error, which we catch and log. This approach provides similar functionality to the Go version’s select statement with channels.