Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Timing in JavaScript

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 timer

2. 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 setTimeout or setInterval.


4. Date and performance for Measuring Time

  • You can measure elapsed time using Date or the higher-precision performance.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!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql