case study:
① After clicking the button, the button will be disabled disabled = true;
② the content inside the button will change, note the contents button which is modified by innerHTML
③ there is a change in the number of seconds, so the need to use the timer
④ define a variable in a timer inside, diminishing
⑤ If the variable is 0, indicating the time necessary to stop the timer and reset button initial state
1, the first step: After clicking the button, the button is disabled
<! DOCTYPE HTML> <HTML lang = " EN " > <head> <Meta charset = " UTF-8 " > <title> the Title </ title> </ head> <body> phone number: <the INPUT of the type = " Number The " > <button> send </ button> <Script> // after clicking the button, disabled for the disabled to true // while the content will change the button inside, note the contents button inside the innerHTML modify // there is a change in seconds and therefore need to use timers // define a variable in a timer inside, diminishing // If the variable is 0 to illustrate the time, we need to stop timer and reset button initial state var btn = the Document.querySelector("button" ); btn.addEventListener('click',function(){ btn.disabled=true; }) </script> </body> </html>
2. The second step: a button inside the contents of the words "5,4,3,2,1 seconds left."
var btn=document.querySelector("button"); btn.addEventListener('click',function(){ var time=5; timer=setInterval(function(){ btn.disabled=true; btn.innerHTML="还剩下"+time+"秒“; time--; },1000) })
3, the third step, when the time becomes 0 seconds, to clear the timer and returns to its original state button
timer=setInterval(function(){ if(time==0) { clearInterval(timer); btn.disabled=false; btn.innerHTML="发送"; time=5; } else{ btn.innerHTML=”还剩下"+time"+“秒"; time--; } },1000)
A bug:
When the time is 0, the button returns to its original state, if you want to click on the "send" button again, you need to re-set the time to "time = 5", but this line of code in time for the next judge to 0, after to 0, do not need to click on, it will automatically start the countdown from 5
Cause: The timer is not cleared, clearInterval timer (timer) is wrong, wrote the time. . . . .