Science Knowings: JavaScript Course For Social Media

setTimeout and setInterval

The Power of setTimeout and setInterval

Welcome to the world of asynchronous JavaScript, where we'll explore the magic of setTimeout and setInterval!

What is setTimeout?

setTimeout is a global function that schedules a function or code block to be executed after a specified delay (in milliseconds).

setTimeout Syntax

setTimeout(function | code block, delayInMilliseconds)

setTimeout Example: Displaying a Message After 2 Seconds

setTimeout(() => { 
  console.log("Hello, world!");
}, 2000);

setTimeout Example 2: Simulating a Loading Screen

Display a loading message for 5 seconds and then remove it.

setTimeout(() => { 
}, 5000);

clearInterval Method: Stopping setTimeout or setInterval

The clearInterval method cancels a setTimeout or setInterval function.

setInterval Syntax

setInterval(function | code block, intervalInMilliseconds)

setInterval Example: Updating a Clock Every Second

Display the current time on the page every second.

setInterval(() => { 
  const date = new Date();
  document.querySelector(".time").textContent = date.toLocaleTimeString();
}, 1000);

setInterval Example 2: Rotating Colors

Change the background color of the page every 3 seconds.

const colors = ["red", "green", "blue"];
let currentIndex = 0;

setInterval(() => { = colors[currentIndex];
  currentIndex = (currentIndex + 1) % colors.length;  
}, 3000);

setTimeout vs setInterval: Key Differences

Feature setTimeout setInterval
Execution Executes once after a delay Executes repeatedly at a specified interval
Stopping Use clearTimeout Use clearInterval

Use Cases of setTimeout and setInterval

  • Displaying alerts or messages
  • Simulating loading screens
  • Creating slideshows
  • Updating clocks and timers
  • Polling for data from a server

Best Practices for Using setTimeout and setInterval

  • Use setTimeout when you want to execute code only once after a delay.
  • Use setInterval when you want to execute code repeatedly at a specified interval.
  • Always clear timeouts and intervals using clearTimeout and clearInterval when you're done with them.

Alternatives to setTimeout and setInterval

  • requestAnimationFrame for animations
  • Promise.setTimeout for better error handling
  • RxJS for managing asynchronous events

Next Topic: Promises

In the next session, we'll dive into the world of promises, a powerful tool for handling asynchronous operations in JavaScript. Follow us to learn more and take your coding skills to the next level!