Tickers in JavaScript

Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

function main() {
    // Tickers use a similar mechanism to timers: a
    // callback function that is executed at regular intervals.
    // Here we'll use setInterval to execute a function
    // every 500ms.
    const ticker = setInterval(() => {
        console.log("Tick at", new Date());
    }, 500);

    // We'll stop our ticker after 1600ms.
    setTimeout(() => {
        clearInterval(ticker);
        console.log("Ticker stopped");
    }, 1600);
}

main();

Tickers can be stopped like timers. Once a ticker is stopped it won’t execute any more callbacks. We’ll stop ours after 1600ms.

When we run this program the ticker should tick 3 times before we stop it.

$ node tickers.js
Tick at 2023-06-08T12:34:56.789Z
Tick at 2023-06-08T12:34:57.290Z
Tick at 2023-06-08T12:34:57.791Z
Ticker stopped

In JavaScript, we use setInterval to create a ticker-like behavior. The setInterval function repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This is similar to a ticker in other languages.

We use setTimeout to stop the ticker after a certain amount of time. The clearInterval function is used to stop the execution of the interval set by setInterval.

Note that JavaScript runs in a single-threaded environment, so this example doesn’t use true concurrency like the original example. However, it demonstrates a similar concept of periodic execution and stopping it after a certain time.