节流方式实现,发送验证码

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <style lang="">
        #btn {
            width: 180px;
            height: 30px;
            border: 2px solid coral;
            text-align: center;
            line-height: 30px;
            cursor: pointer;
            user-select: none;
        }
    </style>
</head>

<body>
    <div id="btn">获取验证码</div>
</body>
<script>
    function submit(e) {
        let t = 10;
        let timer;
        e.target.innerText = t;
        e.target.style.cursor = 'not-allowed';
        e.target.style.color = 'red';
        e.target.style.backgroundColor = '#ccc';

        timer = setInterval(() => {
            e.target.innerText = --t;
            if (t === 0) {
                clearInterval(timer)
                e.target.style.cursor = 'pointer';
                e.target.innerText = '获取验证码';
                e.target.style.color = '#000';
                e.target.style.backgroundColor = '#fff';
            }
        }, 1000)

    }
    function throttle1(fn, wait) {
        let timer = null;
        return function () {
            if (!timer) {  //当定时器有值的时候,不执行
                fn.apply(this, arguments);  //点击立即执行
                timer = setTimeout(() => {
                    timer = null;
                }, wait)
            }
        }
    }
    btn.addEventListener('click', throttle1(submit, 10000))



</script>

</html>
posted on 2024-03-01 19:33  Steven_YF  阅读(4)  评论(0编辑  收藏  举报