JavaScript短信验证码倒计时是一种常见的功能,用于在用户请求发送短信验证码后,限制用户在一定时间内再次请求发送验证码。这样可以防止恶意用户频繁请求验证码,保护服务器资源和用户信息安全。
常见的倒计时类型包括固定时间倒计时(如60秒)和动态时间倒计时(根据用户行为调整)。
以下是一个简单的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>
localStorage
或sessionStorage
保存倒计时状态,页面加载时恢复倒计时。通过以上方法,可以有效实现并优化短信验证码倒计时功能,提升用户体验和应用安全性。