input with timer in javascript

You can use setInterval() function to execute a code repeatedly with a fixed time delay between each execution.

Here is an example of how to use setInterval() to get user input with a timer:

index.tsx
let userInput = ''; // declare a variable to store user input

const intervalId = setInterval(() => {
  // prompt the user for input
  userInput = prompt('Enter something');

  // check if user has entered a value
  if (userInput !== null) {
    console.log(`User entered: ${userInput}`);
  } else {
    clearInterval(intervalId); // clear the interval if the user cancels the input
  }
}, 2000); // time interval in milliseconds (2000ms or 2 seconds in this case)

466 chars
15 lines

In this example, the code will prompt the user for input every 2 seconds. If the user enters something, the input will be logged to the console. If the user cancels the input, the interval will be cleared using clearInterval() function.

related categories

gistlibby LogSnag