JavaScript--setTimeout 与 clearTimeout,setInterval和clearInterval
·
setTimeout
功能
setTimeout() 方法用于在指定的毫秒数后执行一次代码或函数。
语法
const timeoutID = setTimeout(function[, delay, arg1, arg2, ...]);
const timeoutID = setTimeout(code[, delay]);
| 参数 | 类型 | 描述 | 必需 |
|---|---|---|---|
function | Function | 要执行的函数 | 是 |
code | String | 要执行的代码字符串(不推荐使用) | 可选 |
delay | Number | 延迟时间(毫秒),默认 0 | 可选 |
arg1, arg2, ... | Any | 传递给函数的参数 | 可选 |
返回值
-
返回一个正整数,表示定时器的ID
-
用于后续通过
clearTimeout()取消定时器
// 基本用法
setTimeout(() => {
console.log('2秒后执行');
}, 2000);
// 带参数
setTimeout((name, age) => {
console.log(`Hello ${name}, you are ${age} years old`);
}, 1000, 'Alice', 25);
// 传递已有函数
function showMessage(message) {
console.log(message);
}
setTimeout(showMessage, 1500, 'Delayed message');
clearTimeout
功能
clearTimeout() 方法用于取消先前通过 setTimeout() 设置的定时器。
语法
clearTimeout(timeoutID);
setInterval
功能
setInterval() 方法用于每隔指定的毫秒数重复执行代码或函数。
语法
const intervalID = setInterval(function[, delay, arg1, arg2, ...]);
const intervalID = setInterval(code[, delay]);
参数说明
| 参数 | 类型 | 描述 | 必需 |
|---|---|---|---|
function | Function | 要重复执行的函数 | 是 |
code | String | 要执行的代码字符串 | 可选 |
delay | Number | 间隔时间(毫秒) | 可选 |
arg1, arg2, ... | Any | 传递给函数的参数 | 可选 |
返回值
-
返回一个正整数,表示间隔定时器的ID
-
用于后续通过
clearInterval()取消定时器
// 基本用法
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`执行次数: ${counter}`);
if (counter >= 5) {
clearInterval(intervalId);
console.log('定时器已停止');
}
}, 1000);
// 带参数
setInterval((index, total) => {
console.log(`进度: ${index}/${total}`);
}, 2000, 1, 10);
更多推荐


所有评论(0)