js实现按钮禁用倒计时

372 阅读1分钟
    <button type="button">测试</button>
        var btn = document.querySelector('button');
        var timer = null;
        btn.onclick = (function() {
            this.disabled = true;
            var n = 10;
            timer = setInterval(function() {
                this.innerText = '距下次点击还剩' + n + '秒';
                n--;
                if (n < 0) {
                    clearInterval(timer);
                    this.disabled = false;
                    this.innerText = '测试';
                }
                console.log(this);
            }.bind(this), 1000);
            //这里使用bind可以用来在不同作用域中调整this指向
        })