js realizes the countdown function of obtaining verification SMS


foreword

Today I will share with you a small function. When we need to obtain a mobile phone verification code or other verification codes to log in, there will be a function. When you click to send the verification code, there will be a countdown. When the countdown is not over, the button is disabled. state to prevent repeated sending of text messages, let's take a look at how to implement this function using JS.

1. Functional analysis

  1. After the button is clicked, the button will be disabled, disable is true.
  2. At the same time, the content inside the button changes, and the content inside the button is modified by innerHTML.
  3. At the same time, the number of seconds sent changes, so we need to use a timer.
  4. Define a variable that is continuously decremented in the timer.
  5. If the variable is 0, it means that the time is up, we need to stop the timer and restore the initial state of the button.

2. Realization

First write our html part:

<input type="number">
<button>获取验证码</button>

Create an input box to enter a mobile phone number and a button to get a verification code.

Then write our js part:

var but = document.querySelector('button');
			var time = 10; //定义剩下的秒数
			but.addEventListener('click', function() {
    
    
				but.disabled = true;
				var timer = setInterval(function() {
    
    
					if (time == 0) {
    
    
						//清除定时器和复原按钮
						clearInterval(timer);
						but.disabled = false;
						but.innerHTML = '发送';
						time = 10; //这个10是重新开始
					} else {
    
    
						but.innerHTML = '剩余' + time + '秒';
						time--;
					}
				}, 1000);
			})

Here's what it looks like without a click:
insert image description here
Here's what it looks like after a click:
insert image description here

Summarize

The time we defined is a countdown time, usually 60 seconds, here is 10 seconds to avoid waiting too long, you can set the countdown time according to your own needs.
The above is the whole content of this chapter, I hope it can help you.

Guess you like

Origin blog.csdn.net/SqlloveSyn/article/details/129822862