js实现验证码倒计时
实现验证码倒计时功能
HTML 部分
<button id="sendCodeBtn">获取验证码</button>
JavaScript 部分

let countdown = 60;
const sendCodeBtn = document.getElementById('sendCodeBtn');
function startCountdown() {
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `${countdown}秒后重新获取`;
const timer = setInterval(() => {
countdown--;
sendCodeBtn.textContent = `${countdown}秒后重新获取`;
if (countdown <= 0) {
clearInterval(timer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '获取验证码';
countdown = 60;
}
}, 1000);
}
sendCodeBtn.addEventListener('click', startCountdown);
优化版本(防止重复点击)
let countdown = 60;
let isCounting = false;
const sendCodeBtn = document.getElementById('sendCodeBtn');
function startCountdown() {
if (isCounting) return;
isCounting = true;
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `${countdown}秒后重新获取`;
const timer = setInterval(() => {
countdown--;
sendCodeBtn.textContent = `${countdown}秒后重新获取`;
if (countdown <= 0) {
clearInterval(timer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '获取验证码';
countdown = 60;
isCounting = false;
}
}, 1000);
}
sendCodeBtn.addEventListener('click', startCountdown);
封装为可复用函数
function createCountdown(btnId, duration = 60) {
const btn = document.getElementById(btnId);
let countdown = duration;
let isCounting = false;
const originalText = btn.textContent;
function start() {
if (isCounting) return;
isCounting = true;
btn.disabled = true;
btn.textContent = `${countdown}秒后重新获取`;
const timer = setInterval(() => {
countdown--;
btn.textContent = `${countdown}秒后重新获取`;
if (countdown <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.textContent = originalText;
countdown = duration;
isCounting = false;
}
}, 1000);
}
btn.addEventListener('click', start);
}
// 使用示例
createCountdown('sendCodeBtn', 60);
注意事项
- 确保按钮元素在DOM加载完成后才执行JavaScript代码
- 实际项目中建议将倒计时状态保存在服务端,防止页面刷新后状态丢失
- 移动端开发时需要考虑点击区域的适当扩大






