Tickers in TypeScript

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.

import { setInterval, clearInterval } from 'timers';

function main() {
    // We'll use setInterval to create a ticker that fires every 500ms
    const ticker = setInterval(() => {
        console.log("Tick at", new Date());
    }, 500);

    // We'll use a Promise to simulate the 'done' channel
    const done = new Promise<void>((resolve) => {
        // Stop the ticker after 1600ms
        setTimeout(() => {
            clearInterval(ticker);
            console.log("Ticker stopped");
            resolve();
        }, 1600);
    });

    // Wait for the done Promise to resolve
    done.then(() => {
        console.log("Program finished");
    });
}

main();

In this TypeScript version, we use setInterval to create a ticker that fires every 500 milliseconds. The clearInterval function is used to stop the ticker, similar to the Stop method in the original example.

Instead of using channels and goroutines, we use a Promise to simulate the ‘done’ channel. The Promise resolves after 1600 milliseconds, at which point we stop the ticker.

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

$ ts-node tickers.ts
Tick at 2023-06-01T12:00:00.000Z
Tick at 2023-06-01T12:00:00.500Z
Tick at 2023-06-01T12:00:01.000Z
Ticker stopped
Program finished

In this TypeScript implementation, we’ve replaced the channel-based concurrency model with Promises and the built-in timer functions. The overall behavior of the program remains the same, demonstrating periodic ticks followed by stopping the ticker.