Appearance
定时器(自动执行代码)
17.1 setInterval 循环定时器
setInterval 方法用于按照指定的时间间隔重复执行一个函数或代码块。
基本语法
javascript
const intervalId = setInterval(function, delay);function:要执行的函数delay:时间间隔,单位为毫秒- 返回值:定时器的 ID,用于后续清除定时器
示例:每秒更新时间
javascript
// 每秒更新一次当前时间
const intervalId = setInterval(function() {
const now = new Date();
const timeString = now.toLocaleTimeString();
console.log(timeString);
}, 1000);
// 5秒后停止定时器
setTimeout(function() {
clearInterval(intervalId);
console.log("定时器已停止");
}, 5000);示例:进度条
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>进度条示例</title>
<style>
.progress-bar {
width: 300px;
height: 20px;
background-color: #f0f0f0;
border-radius: 10px;
overflow: hidden;
}
.progress {
height: 100%;
background-color: #4CAF50;
width: 0%;
transition: width 0.3s ease;
}
</style>
</head>
<body>
<div class="progress-bar">
<div class="progress" id="progress"></div>
</div>
<p id="percent">0%</p>
<script>
const progress = document.getElementById("progress");
const percent = document.getElementById("percent");
let width = 0;
const intervalId = setInterval(function() {
if (width >= 100) {
clearInterval(intervalId);
percent.textContent = "100%";
} else {
width++;
progress.style.width = width + "%";
percent.textContent = width + "%";
}
}, 50);
</script>
</body>
</html>17.2 setTimeout 延迟定时器
setTimeout 方法用于在指定的时间后执行一次函数或代码块。
基本语法
javascript
const timeoutId = setTimeout(function, delay);function:要执行的函数delay:延迟时间,单位为毫秒- 返回值:定时器的 ID,用于后续清除定时器
示例:延迟执行
javascript
console.log("开始");
// 2秒后执行
setTimeout(function() {
console.log("2秒后执行");
}, 2000);
console.log("结束");
// 输出顺序:
// 开始
// 结束
// 2秒后执行示例:防抖函数
javascript
// 防抖函数:在一定时间内多次触发,只执行最后一次
function debounce(func, delay) {
let timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
}
// 使用防抖函数
const debouncedSearch = debounce(function(keyword) {
console.log("搜索:", keyword);
// 这里可以执行实际的搜索操作
}, 500);
// 模拟用户输入
debouncedSearch("J");
debouncedSearch("Ja");
debouncedSearch("Jav");
debouncedSearch("Java");
debouncedSearch("JavaScript");
// 只有最后一次会执行:搜索:JavaScript17.3 清除定时器
清除 setInterval
使用 clearInterval 方法清除 setInterval 创建的定时器。
javascript
const intervalId = setInterval(function() {
console.log("执行中...");
}, 1000);
// 清除定时器
clearInterval(intervalId);清除 setTimeout
使用 clearTimeout 方法清除 setTimeout 创建的定时器。
javascript
const timeoutId = setTimeout(function() {
console.log("执行");
}, 2000);
// 清除定时器
clearTimeout(timeoutId);17.4 实战:倒计时 / 轮播图自动切换
实战 1:倒计时
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>倒计时示例</title>
<style>
.countdown {
font-size: 48px;
font-weight: bold;
text-align: center;
margin: 50px 0;
}
</style>
</head>
<body>
<div class="countdown" id="countdown">10</div>
<button id="startBtn">开始倒计时</button>
<button id="stopBtn">停止倒计时</button>
<script>
const countdown = document.getElementById("countdown");
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
let timeLeft = 10;
let intervalId;
function startCountdown() {
// 重置时间
timeLeft = 10;
countdown.textContent = timeLeft;
// 清除之前的定时器
if (intervalId) {
clearInterval(intervalId);
}
// 开始倒计时
intervalId = setInterval(function() {
timeLeft--;
countdown.textContent = timeLeft;
if (timeLeft <= 0) {
clearInterval(intervalId);
countdown.textContent = "时间到!";
}
}, 1000);
}
function stopCountdown() {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
}
startBtn.addEventListener("click", startCountdown);
stopBtn.addEventListener("click", stopCountdown);
</script>
</body>
</html>实战 2:轮播图自动切换
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图示例</title>
<style>
.slider {
position: relative;
width: 600px;
height: 300px;
margin: 50px auto;
overflow: hidden;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
width: 600px;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
font-size: 36px;
font-weight: bold;
color: white;
}
.slide:nth-child(1) { background-color: #f44336; }
.slide:nth-child(2) { background-color: #2196f3; }
.slide:nth-child(3) { background-color: #4caf50; }
.slide:nth-child(4) { background-color: #ff9800; }
.controls {
text-align: center;
margin-top: 20px;
}
button {
padding: 10px 20px;
margin: 0 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="slider">
<div class="slides" id="slides">
<div class="slide">幻灯片 1</div>
<div class="slide">幻灯片 2</div>
<div class="slide">幻灯片 3</div>
<div class="slide">幻灯片 4</div>
</div>
</div>
<div class="controls">
<button id="prevBtn">上一张</button>
<button id="nextBtn">下一张</button>
<button id="autoBtn">自动播放</button>
<button id="stopBtn">停止播放</button>
</div>
<script>
const slides = document.getElementById("slides");
const prevBtn = document.getElementById("prevBtn");
const nextBtn = document.getElementById("nextBtn");
const autoBtn = document.getElementById("autoBtn");
const stopBtn = document.getElementById("stopBtn");
const slideCount = 4;
let currentIndex = 0;
let intervalId;
function updateSlide() {
slides.style.transform = `translateX(-${currentIndex * 600}px)`;
}
function nextSlide() {
currentIndex = (currentIndex + 1) % slideCount;
updateSlide();
}
function prevSlide() {
currentIndex = (currentIndex - 1 + slideCount) % slideCount;
updateSlide();
}
function startAutoPlay() {
intervalId = setInterval(nextSlide, 2000);
}
function stopAutoPlay() {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
}
// 事件监听
nextBtn.addEventListener("click", nextSlide);
prevBtn.addEventListener("click", prevSlide);
autoBtn.addEventListener("click", startAutoPlay);
stopBtn.addEventListener("click", stopAutoPlay);
// 初始自动播放
startAutoPlay();
</script>
</body>
</html>小结
setInterval:按照指定的时间间隔重复执行函数setTimeout:在指定的时间后执行一次函数clearInterval:清除setInterval创建的定时器clearTimeout:清除setTimeout创建的定时器- 定时器返回的 ID 是唯一的,用于后续清除定时器
- 定时器在网页开发中常用于:
- 实时更新数据(如时间、股票价格)
- 动画效果
- 自动轮播
- 倒计时
- 防抖和节流
- 使用定时器时要注意及时清除,避免内存泄漏
