Timers in TypeScript
import { setTimeout, clearTimeout } from 'timers';
function main() {
// Timers represent a single event in the future. You
// tell the timer how long you want to wait, and it
// provides a callback that will be executed at that
// time. This timer will wait 2 seconds.
const timer1 = setTimeout(() => {
console.log("Timer 1 fired");
}, 2000);
// If you just wanted to wait, you could have used
// a simple setTimeout. One reason a timer may be useful is
// that you can cancel the timer before it fires.
// Here's an example of that.
const timer2 = setTimeout(() => {
console.log("Timer 2 fired");
}, 1000);
clearTimeout(timer2);
console.log("Timer 2 stopped");
// Give the timer2 enough time to fire, if it ever
// was going to, to show it is in fact stopped.
setTimeout(() => {
// This is just to keep the program running
}, 2000);
}
main();
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:
$ ts-node timers.ts
Timer 2 stopped
Timer 1 fired
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.