ReasonJun

javascript : Timer API , scheduling 본문

Frontend/Javasciprt

javascript : Timer API , scheduling

ReasonJun 2023. 6. 8. 16:52
728x90

In JavaScript, the Timer API provides functions and methods to schedule and manage timers. Timers allow you to execute code at specified intervals or after a certain delay. The Timer API consists of two main functions: setTimeout and setInterval, along with their corresponding methods to clear or cancel the timers: clearTimeout and clearInterval.

Here's an overview of the Timer API in JavaScript:

  • setTimeout:

The setTimeout function is used to schedule the execution of a function once after a specified delay. It takes two parameters: a function to be executed and a delay time in milliseconds. After the specified delay, the provided function is invoked.

setTimeout(function() {
  console.log('Delayed message');
}, 2000); // Executes after a 2000ms (2-second) delay
  • setInterval:

The setInterval function is used to repeatedly execute a function at a specified interval. It takes two parameters: a function to be executed and an interval time in milliseconds. The function is called repeatedly, with each execution occurring after the specified interval.

setInterval(function() {
  console.log('Repeated message');
}, 1000); // Executes every 1000ms (1 second)
  • clearTimeout:

The clearTimeout method is used to cancel a timer that was set using setTimeout. It takes the timer identifier returned by setTimeout as a parameter.

const timerId = setTimeout(function() {
  console.log('Delayed message');
}, 2000);

clearTimeout(timerId); // Cancels the timer before it executes
  • clearInterval:

The clearInterval method is used to stop the execution of a function that was repeatedly called using setInterval. It takes the timer identifier returned by setInterval as a parameter.

const timerId = setInterval(function() {
  console.log('Repeated message');
}, 1000);

clearInterval(timerId); // Stops the execution of the function
728x90
Comments