Scheduling: setTimeout and setInterval

Scheduling: setTimeout and setInterval

Scheduling in JavaScript: setTimeout & setInterval

JavaScript provides two main scheduling functions to execute code after a delay or repeatedly at intervals:

  1. setTimeout → Runs a function once after a delay.
  2. setInterval → Runs a function repeatedly at fixed intervals.

1️⃣ setTimeout – Delayed Execution

setTimeout executes a function after a specified time (in milliseconds).

Syntax

setTimeout(function, delay, param1, param2, ...);
  • function → Function to execute
  • delay → Time in milliseconds (1 second = 1000 ms)
  • param1, param2, ... → Optional parameters for the function

Example: Delay Execution by 2 Seconds

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

Example: Passing Arguments

function greet(name) { console.log(`Hello, ${name}!`); } setTimeout(greet, 3000, "Alice"); // Runs after 3 seconds

Cancel setTimeout with clearTimeout

If you need to cancel a scheduled timeout, use clearTimeout.

const timeoutId = setTimeout(() => { console.log("This will not run."); }, 5000); clearTimeout(timeoutId); // Cancels the timeout

2️⃣ setInterval – Repeated Execution

setInterval executes a function at regular intervals (repeats indefinitely).

Syntax

setInterval(function, interval, param1, param2, ...);
  • function → Function to execute
  • interval → Time interval in milliseconds
  • param1, param2, ... → Optional parameters

Example: Run Every 1 Second

setInterval(() => { console.log("This runs every second."); }, 1000);

Example: Passing Arguments

function showTime(name) { console.log(`${name}, current time is: `, new Date().toLocaleTimeString()); } setInterval(showTime, 2000, "Alice"); // Runs every 2 seconds

Cancel setInterval with clearInterval

To stop a repeating interval, use clearInterval.

const intervalId = setInterval(() => { console.log("This will repeat every 2 seconds."); }, 2000); setTimeout(() => { clearInterval(intervalId); // Stops the interval after 6 seconds console.log("Interval stopped."); }, 6000);

3️⃣ When to Use setTimeout vs. setInterval?

FeaturesetTimeoutsetInterval
Runs once?✅ Yes❌ No (Repeats)
Runs repeatedly?❌ No✅ Yes
Can be canceled?clearTimeout()clearInterval()
Best for?Delayed executionPeriodic updates

4️⃣ Alternative to setInterval – Recursive setTimeout

A better alternative to setInterval is using recursive setTimeout, which ensures accurate timing.

function repeatTask() { console.log("Task executed!"); setTimeout(repeatTask, 2000); // Calls itself after 2 seconds } repeatTask();

Why use this?

  • Prevents overlapping executions if a previous task is still running.
  • More accurate than setInterval for long tasks.

Conclusion

setTimeout → Executes a function once after a delay.
setInterval → Repeats execution at fixed intervals.
✔ Use clearTimeout / clearInterval to cancel scheduled tasks.
✔ For more control, use recursive setTimeout instead of setInterval.

🚀 Need more examples? Let me know! 😃

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close