create a timer 1 minute and return string in javascript

To create a timer in JavaScript, you can use setInterval function which executes a function repeatedly after a fixed time interval. Here is an example code that creates a timer for 1 minute and returns a string after the timer is expired:

index.tsx
function createTimer(callback) {
  let timeLeft = 60; // 1 minute
  const interval = setInterval(() => {
    if (timeLeft <= 0) {
      clearInterval(interval);
      callback("Timer expired");
    } else {
      console.log(`Time left: ${timeLeft--} seconds`);
    }
  }, 1000); // 1000 ms interval
}

// Usage:
createTimer((msg) => {
  console.log(msg);
});
360 chars
17 lines

In this example, createTimer function takes a callback function as a parameter which will be executed after the timer is expired. It uses setInterval to execute a function after every 1000 ms (1 second). Within the interval function, we check if the time left is less than or equal to 0, then we clear the interval and call the callback function with a message "Timer expired". Otherwise, we log the time left to the console.

To use this function, you can call createTimer and pass a function that will be called after the timer is completed. In the example, we are passing a callback function that logs the message to the console.

gistlibby LogSnag