Timers in TypeScript
In TypeScript, we use the setTimeout
function to create timers. This function takes a callback and a delay in milliseconds. The callback will be executed after the specified delay.
To cancel a timer, we use the clearTimeout
function. This is equivalent to the Stop
method in the original example.
Note that TypeScript (and JavaScript) run in a single-threaded environment by default, so we don’t need to use any concurrency primitives like channels or goroutines.
To run this program:
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
In a browser environment, you would typically see similar behavior, although the exact timing might vary slightly depending on the browser’s event loop implementation.
TypeScript doesn’t have a direct equivalent to Go’s time.Sleep
. In this example, we use a second setTimeout
at the end of the main
function to keep the program running long enough to demonstrate the behavior of the timers. In a real-world scenario, you typically wouldn’t need this, as JavaScript/TypeScript programs often run in event-driven environments where the program keeps running as long as there are pending timers or other asynchronous operations.
Next example: Tickers.