短信验证码倒计时是一种常见的安全验证机制,用于防止恶意用户频繁请求验证码。它通常在前端通过 JavaScript 实现,限制用户在一定时间内只能请求一次验证码。
以下是一个简单的短信验证码倒计时 JavaScript 示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>短信验证码倒计时</title>
</head>
<body>
<button id="sendCodeBtn">发送验证码</button>
<script>
let countdown = 60; // 倒计时时间,单位秒
let timer = null;
const sendCodeBtn = document.getElementById('sendCodeBtn');
sendCodeBtn.addEventListener('click', function() {
if (countdown === 60) {
// 模拟发送验证码请求
console.log('发送验证码请求...');
startCountdown();
}
});
function startCountdown() {
timer = setInterval(() => {
countdown--;
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `${countdown}秒后重试`;
if (countdown <= 0) {
clearInterval(timer);
countdown = 60;
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '发送验证码';
}
}, 1000);
}
</script>
</body>
</html>
setInterval
的执行时间不精确。setTimeout
递归调用,确保每次倒计时都是基于上一次的实际结束时间。function startCountdown() {
function tick() {
countdown--;
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `${countdown}秒后重试`;
if (countdown > 0) {
setTimeout(tick, 1000);
} else {
countdown = 60;
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '发送验证码';
}
}
tick();
}
localStorage
或 sessionStorage
存储倒计时状态。function startCountdown() {
const storedCountdown = localStorage.getItem('countdown');
if (storedCountdown) {
countdown = parseInt(storedCountdown, 10);
}
function tick() {
countdown--;
localStorage.setItem('countdown', countdown);
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `${countdown}秒后重试`;
if (countdown > 0) {
setTimeout(tick, 1000);
} else {
localStorage.removeItem('countdown');
countdown = 60;
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = '发送验证码';
}
}
tick();
}
通过以上方法,可以有效实现短信验证码的倒计时功能,并解决常见的问题。
没有搜到相关的文章