这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
这篇文章主要为大家详细介绍了 js 实现 5 秒倒计时重新发送短信功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例讲述了 js 实现倒计时重新发送短信验证码功能的方法。分享给大家供大家参考,具体如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- js-手机发送短信倒计时
- </title>
- <style>
- button{ width: 100px; height: 30px; border: none; } input{ outline: none;
- }
- </style>
- <script>
- window.onload = function() {
- function $(id) {
- return document.getElementById(id);
- }
- $('btn').onclick = function() {
- clearInterval(timer); //清除计时器
- var that = this;
- that.disabled = true;
- var count = 5;
- var timer = setInterval(function() {
- if (count > 0) {
- count--;
- that.innerHTML = "剩余时间" + count + "s";
- } else {
- that.innerHTML = "重新发送短信";
- that.disabled = false;
- clearInterval(timer); //清除计时器
- }
- },
- 1000);
- }
- }
- </script>
- </head>
- <body>
- <div class="box">
- <input type="text" id="txt">
- <button id="btn">
- 点击发送短信
- </button>
- </div>
- </body>
- </html>
或者使用 setTimeout 来模拟,一般情况下,还是推荐使用 setTimeout,更安全一些。当使用 setInterval(fn,1000) 时,程序是间隔 1s 执行一次,但是每次程序执行是需要 3s,那么就要等程序执行完才能执行下一次,即实际间隔时间为(间隔时间和程序执行时间两者的最大值)。而 setTimeout(fn,1000), 代表的是,延迟 1s 再执行程序,且仅执行一次。每次程序执行是需要 3s,所以实际时间为 1s+3s=4s。可以使用 setTimeout 递归调用来模拟 setInterval。
- <script>
- window.onload = function() {
- function $(id) {
- return document.getElementById(id);
- }
- $('btn').onclick = function() {
- var that = this;
- that.disabled = true;
- var count = 5;
- var timer = setTimeout(fn, 1000);
- function fn() {
- count--;
- if (count > 0) {
- that.innerHTML = "剩余时间" + count + "s";
- setTimeout(fn, 1000);
- } else {
- that.innerHTML = "重新发送短信";
- that.disabled = false;
- }
- }
- }
- }
- </script>
来源: http://www.phperz.com/article/17/0602/328016.html