Timers in JavaScript

const timers = require('timers');

// We often want to execute JavaScript code at some point in the
// future, or repeatedly at some interval. JavaScript's built-in
// setTimeout and setInterval functions make both of these tasks easy.

// Timers represent a single event in the future. You
// tell the timer how long you want to wait, and it
// will execute a callback function 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);

// We can cancel the timer before it has a chance to fire
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);

In JavaScript, we use setTimeout to create timers that execute a function after a specified delay. The clearTimeout function is used to cancel a timer before it fires.

To run this program:

$ node timers.js
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.

Note that JavaScript is single-threaded and uses an event loop for handling asynchronous operations. Unlike Go, we don’t need to explicitly block or use channels to wait for timer events. The callback functions are automatically executed when the timer fires.

Also, in a browser environment, you would typically see these timer functions as global objects (window.setTimeout, window.clearTimeout). In a Node.js environment, they are part of the global scope or can be imported from the ’timers’ module as shown in the example.