JavaScript setInterval & setTimeout Guide
In JavaScript, both setInterval and setTimeout are methods used to execute a piece of code at a specific time interval in the future.
- Set a recurring interval
// 每隔1秒执行一次
setInterval(function() {
console.log('Hello');
}, 1000);
- Delay the execution of a piece of code.
// 2秒后执行一次
setTimeout(function() {
console.log('Hello');
}, 2000);
setInterval will repeatedly execute a specified function at specific time intervals, whereas setTimeout will only execute the specified function once.