How to create a timer in JavaScript?
To create a timer in JavaScript, you can use the setInterval
function, which will execute a specified function repeatedly at a given interval.
Here’s an example of how you can use setInterval
to create a timer that counts down from 10 to 0:
let count = 10; const countdown = setInterval(function() { count--; console.log(count); if (count === 0) { clearInterval(countdown); console.log('Done!'); } }, 1000); // 1000 milliseconds = 1 second
This code will log the countdown to the console every second until the count reaches 0, at which point it will clear the interval and log “Done!”.
You can also use the setTimeout
function to create a timer that executes a function once after a given time period. For example:
setTimeout(function() { console.log('Done!'); }, 5000); // 5000 milliseconds = 5 seconds
This code will log “Done!” to the console after 5 seconds.