Home > Web Front-end > JS Tutorial > body text

What is the difference between setInterval and setTimeout in JavaScript?

Linda Hamilton
Release: 2024-11-20 00:45:03
Original
615 people have browsed it

What is the difference between setInterval and setTimeout in JavaScript?

Understanding the Distinction Between 'setInterval' and 'setTimeout'

The JavaScript functions 'setInterval' and 'setTimeout' serve distinct purposes in managing time intervals. Let's delve into the key difference between them:

setInterval vs. setTimeout

'setInterval' and 'setTimeout' differ primarily in their execution frequency.

  • setTimeout: Executes a specified code or function once after a set time interval.
  • setInterval: Executes a code or function repeatedly at predefined intervals, indefinitely or until cleared.

Example Code

Consider these code examples to illustrate their functionality:

var intervalID = setInterval(alert, 1000); // Alert every second
// You can clear the interval later: clearInterval(intervalID);

setTimeout(alert, 1000); // Alert once, after a second
Copy after login

In the 'setInterval' example, the alert function will continue to be executed every second. In contrast, 'setTimeout' will trigger the alert only once, after the specified delay of 1000 milliseconds (1 second).

The above is the detailed content of What is the difference between setInterval and setTimeout in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template