JavaScript realizes the countdown effect of obtaining the verification code

Claim:

发送After clicking , the button is disabled and a countdown appears. Set to 5 seconds countdown.
Insert picture description here
After 5 seconds, the button is restored and can be clicked again 发送.
Insert picture description here

Realization ideas:

  1. After the button is clicked, disable it disabledastrue
  2. At the same time, the content inside the button will change, buttonand the content inside will be innerHTMLmodified
  3. The number of seconds inside changes, so you need to use a timer
  4. Define a variable, in the timer, keep decreasing
  5. If the variable is 0, it means the time is up, you need to stop the timer, restore the variable, and restore the initial state of the button

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    手机号码: <input type="text"> <button>发送</button>
    <script>
        // 按钮点击之后,会禁用 disabled 为true 
        // 同时按钮里面的内容会变化, 注意 button 里面的内容通过 innerHTML修改
        // 里面秒数是有变化的,因此需要用到定时器
        // 定义一个变量,在定时器里面,不断递减
        // 如果变量为0 说明到了时间,我们需要停止定时器,并且复原按钮初始状态
        var btn = document.querySelector('button');
        var time = 5; // 定义剩下的秒数
        btn.addEventListener('click', function() {
     
     
            btn.disabled = true;
            var timer = setInterval(function() {
     
     
                if (time == 0) {
     
     
                    // 清除定时器和复原按钮
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = '发送';
                    time = 5; // 重新赋值时间变量
                } else {
     
     
                    btn.innerHTML = time + '秒后可再次发送';
                    time--;
                }
            }, 1000);
        });
    </script>

</body>

</html>

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109270555