To make a timer in javascript,we can use the following functions:
1. setTimeout
2. setInterval
setTimeout:
using set time out , we can trigger a specific function 'once' in a given amount of time.
for example:
function myFunction() {
console.log("Timer is done!");
}
// Set a timer to call myFunction after 2000 milliseconds (2 seconds)
const timerId = setTimeout(myFunction, 2000);
// You can cancel the timer before it executes using clearTimeout
// clearTimeout(timerId);
--------------------------------------------------------------------
setInterval:
using setInterval , we can trigger a function 'repeatedly' with a break of specified time.
for example:
----------------------------------------------------------------------------------------------------------
function myFunction() {
console.log("Timer is running!");
}
// Set a timer to call myFunction every 1000 milliseconds (1 second)
const timerId = setInterval(myFunction, 1000);
// To stop the interval, use clearInterval
// clearInterval(timerId);
Thanks for reading
Comments
Post a Comment