Js Timing in JavaScript
? JavaScript Timing
JavaScript provides several functions and methods to work with timing — to delay execution, repeat actions, or measure time.
Key Timing Functions
1. setTimeout()
Executes a function once after a specified delay (in milliseconds).
setTimeout(() => { console.log("Executed after 2 seconds");}, 2000);Returns a timeout ID which can be used to cancel the timeout with
clearTimeout().
const timerId = setTimeout(() => console.log("Hello"), 3000);clearTimeout(timerId); // cancels the timer2. setInterval()
Repeats execution of a function every specified interval (milliseconds).
const intervalId = setInterval(() => { console.log("Repeating every 1 second");}, 1000);Use
clearInterval()to stop the repeated execution.
clearInterval(intervalId);3. clearTimeout() and clearInterval()
Cancel a scheduled timeout or interval using the ID returned by
setTimeoutorsetInterval.
4. Date and performance for Measuring Time
You can measure elapsed time using
Dateor the higher-precisionperformance.now().
const start = Date.now();// some codeconst end = Date.now();console.log(`Elapsed: ${end - start} ms`);Or:
const start = performance.now();// some codeconst end = performance.now();console.log(`Elapsed: ${end - start} milliseconds`);Example: Using setTimeout and setInterval
// Run once after 3 secondssetTimeout(() => console.log("Timeout executed!"), 3000);// Run every 2 secondsconst timer = setInterval(() => console.log("Interval running..."), 2000);// Stop interval after 10 secondssetTimeout(() => { clearInterval(timer); console.log("Interval cleared");}, 10000);If you want, I can help you with more advanced timing examples like debouncing, throttling, or async timers!