JAVASCRIPT Tutorial

JS Timing

Key Concepts:

  • Timing: Controlling when and how often JavaScript code runs.
  • setTimeout(): Schedules code to run once after a specified delay.
  • setInterval(): Schedules code to run repeatedly at specified intervals.
  • Timers: Background tasks that execute JavaScript code at specified times.
  • Code Execution Timing: The order in which JavaScript code is executed.

Practical Steps:

  1. Set a Timer: Use setTimeout() to schedule code to run once after a delay (in milliseconds):
setTimeout(() => {
  console.log("Code executes after 5 seconds");
}, 5000);
  1. Set an Interval: Use setInterval() to schedule code to run repeatedly at an interval:
setInterval(() => {
  console.log("Code executes every 2 seconds");
}, 2000);
  1. Clear a Timer: Use clearTimeout() or clearInterval() to stop a previously set timer:
// Clear a timeout
clearTimeout(timeoutId);

// Clear an interval
clearInterval(intervalId);
  1. Code Execution Timing: JavaScript code executes asynchronously, meaning it runs in the background without blocking other code. Use async functions and promises to control the order of execution.

Example:

console.log("Start");

setTimeout(() => {
  console.log("Code runs after 2 seconds");
}, 2000);

console.log("Continue");

Output:

Start
Continue
Code runs after 2 seconds

This demonstrates how JavaScript code continues to execute even after a setTimeout() call. The "Code runs after 2 seconds" message appears after the "Continue" message, indicating asynchronous execution.