search
HomeWeb Front-endJS TutorialjQuery implementation code for countdown and SMS countdown functions

jQuery implementation code for countdown and SMS countdown functions

Feb 05, 2018 pm 02:24 PM
jqueryCountdownShort message

This article mainly shares with you jQuery's countdown function and jQuery's countdown function for sending text messages. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

In practical applications, the countdown effect is often used. The following code uses jQuery to implement a countdown timer.

<!DOCTYPE html> 
<html> 
 <head> 
  <meta charset="UTF-8"> 
  <title>jquery倒计时实现</title> 
  <style type="text/css"> 
   .shop_list ul li{ 
    display: inline-block; 
    list-style: none; 
    width: 300px; 
   } 
  </style> 
 </head> 
 <body> 
  <p class="shop_list" id="shop_list"> 
   <ul> 
    <li> 
     <img  src="/static/imghwm/default1.png"  data-src="img/index/zixun1.jpg"  class="lazy"  / alt="jQuery implementation code for countdown and SMS countdown functions" > 
     <p class="listItem"> 
      <h5 id="小米手机-nbsp-Note-nbsp-顶配版">小米手机 Note 顶配版</h5> 
      <p>全网通 香槟金 移动联通<br/>双4G手机 双卡双待</p> 
      <em>¥2998<i>起</i></em> 
      <span class="time" data-starttime="1445982375" data-endtime="1446350400"></span> 
     </p> 
    </li> 
    <li> 
     <img  src="/static/imghwm/default1.png"  data-src="img/index/zixun1.jpg"  class="lazy"  / alt="jQuery implementation code for countdown and SMS countdown functions" > 
     <p class="listItem"> 
      <h5 id="小米手机-nbsp-Note-nbsp-顶配版">小米手机 Note 顶配版</h5> 
      <p>全网通 香槟金 移动联通<br/>双4G手机 双卡双待</p> 
      <em>¥2998<i>起</i></em> 
      <span class="time" data-starttime=&#39;1445982375&#39; data-endtime=&#39;1446350400&#39;></span> 
     </p> 
    </li> 
   </ul> 
  </p> 
 </body> 
 <script type="text/javascript" src="js/lib/jquery-1.10.1.min.js" ></script> 
 <script type="text/javascript"> 
  $(function(){ 
   //找到商品列表以及时间显示span 
   var abj = $("#shop_list"), 
    timeObj = abj.find(&#39;.time&#39;); 
   //获取开始时间 
   var starttime = timeObj.data(&#39;starttime&#39;); 
    
   // 定时器函数 
   function actionDo(){ 
    return setInterval(function(){ 
     timeObj.each(function(index, el) { 
      //surplusTime为活动剩余开始时间 
      var t = $(this), 
       surplusTime = t.data(&#39;endtime&#39;) -starttime; 
      //若活动剩余开始时间小于0,则说明活动已开始 
      if (surplusTime <= 0) { 
       t.html("活动已经开始"); 
      } else{ 
      //否则,活动未开始,将剩余的时间转换成年,月,日,时,分,秒的形式 
       var year = surplusTime/(24*60*60*365), 
        showYear = parseInt(year), 
        month = (year-showYear)*12, 
        showMonth = parseInt(month), 
        day = (month-showMonth)*30, 
        showDay = parseInt(day), 
        hour = (day-showDay)*24, 
        showHour = parseInt(hour), 
        minute = (hour-showHour)*60, 
        showMinute = parseInt(minute), 
        seconds = (minute-showMinute)*60, 
        showSeconds = parseInt(seconds); 
       t.html(""); 
       //设置输出到HTML的格式并输出到HTML 
       if (showYear>0) { 
        t.append("<span>"+showYear+"年</span>") 
       }; 
       if (showMonth>0) { 
        t.append("<span>"+showMonth+"月</span>") 
       }; 
       if (showDay>0) { 
        t.append("<span>"+showDay+"天</span>") 
       }; 
       if (showHour>=0) { 
        t.append("<span>"+showHour+"小时</span>") 
       }; 
       if (showMinute>=0) { 
        t.append("<span>"+showMinute+"分钟</span>") 
       }; 
       if (showSeconds>=0) { 
        t.append("<span>"+showSeconds+"秒</span>") 
       }; 
      }; 
     }); 
     starttime++; 
    },1000); // 设定执行或延时时间 
   }; 
   // 执行它 
   actionDo(); 
  }); 
 </script> 
</html>

How to implement jQuery SMS countdown function

1. When you click the button, you can count down and customize the countdown. 2. When receiving the SMS fails, count down To stop, you can click to resend the text message. 3. The clicked element supports general tags and input tags. Although it seems very complicated, the implementation code is actually very simple. Let me share the implementation code with you. Friends who need it can refer to it.

The main functions implemented are as follows:

1. When you click the button, you can count down and customize the countdown.

2. When receiving the text message fails, the countdown stops and you can click to resend the text message.

3. The clicked element supports general tags and input tags.

html code:

<input type="button" class="sameBtn btnCur" value="发送验证码"/>
<p class="sameBtn btnCur2">发送验证码</p>

css code:

body{padding:100px;text-align: center;}
.sameBtn{display: inline-block;font-size:12px;cursor:pointer;width:76px;height:25px;line-height: 25px;text-align: center;border:0;background: #3186df;color:#fff;}
.sameBtn.current{background: #b1b1b1;}

js code:

   
//短信倒计时功能
/**使用方式如下:
 * $(".btnCur").CountDownF({
 *    time:120,
 *     resetWords:&#39;重新发送&#39;, //文字定义
 *    cnSeconds:&#39;s&#39;,//倒计时中显示中文的秒,还是s
 *    clickClass:&#39;current&#39;, //点击后添加的class类
 *    countState:true,
 *    callback:function(){
 *      setTimeout(function(){
 *       //当发送失败后,可以立即清除倒计时与其状态
 *        $(".btnCur").CountDownF(&#39;clearState&#39;);
 *      },3000);
 *    }
 *  });
 *
 * */
;(function($,window,document,undefined){
  var pluginName = &#39;CountDownF&#39;,
  defaluts = {
    time:120,
    resetWords:&#39;重新发送&#39;, //文字定义
    cnSeconds:&#39;s&#39;,//倒计时中显示中文的秒,还是s
    clickClass:&#39;current&#39;, //点击后添加的class类
    countState:true //是否可以倒计时,true可以倒计时,false不能进行倒计时
  }
  function Count(element,options){
    this.element = element;
    this.$element = $(this.element);
    this.state = true;
    this.settings = $.extend({},defaluts,options);
    this.number = this.settings.time;
    this.init();
  }
  Count.prototype = {
    init:function(){
      var self = this;
      self.$element.on(&#39;click&#39;,function(){
        if(self.state && self.settings.countState){
          self.state = false;
          if(self.settings.countState){
            self._count();
          }
          if(self.settings.callback){
            self.settings.callback();
          }
        }
      });
    },
    //倒计时函数
    _count:function(){
      var self = this;
      if(self.number == 0){
        self._clearInit();
      }else{
        if(self.number < 10){
          //如果当前元素是input,使用val赋值
          this.$element.attr(&#39;type&#39;) ? this.$element.val(&#39;0&#39; + self.number + self.settings.cnSeconds) : this.$element.html(&#39;0&#39; + self.number + self.settings.cnSeconds); 
        }else{
          this.$element.attr(&#39;type&#39;) ? this.$element.val(self.number + self.settings.cnSeconds) : this.$element.html(self.number + self.settings.cnSeconds);
        }
        self.number--;
        this.$element.addClass(self.settings.clickClass);
        self.clearCount = setTimeout(function(){
          self._count();
        },1000);
      }
    },
    //修改是否可发送短信验证码倒计时状态
    change:function(state){
      var self = this;
      self.settings.countState = state;
    },
    //置为初始状态
    _clearInit:function(){
      var self = this;
      self.$element.removeClass(self.settings.clickClass);
      self.$element.attr(&#39;type&#39;) ? self.$element.val(self.settings.resetWords) : self.$element.html(self.settings.resetWords);
      clearTimeout(self.clearCount);
      self.number = self.settings.time;
      self.state = true;
    },
    //清除倒计时进行状态
    clearState:function(){
      var self = this;
      self._clearInit();
    }
  };
  $.fn.CountDownF = function(options){
    var args = arguments;
    if(options === undefined || typeof options ===&#39;object&#39; ){
      return this.each(function(){
        if(!$.data(this,&#39;plugin&#39; + pluginName)){
          $.data(this,&#39;plugin&#39; + pluginName,new Count(this,options));
        }
      });
    }
    else if(typeof options === &#39;string&#39; && options !== &#39;init&#39;){
      var returns;
       this.each(function(){
        var data = $.data(this,&#39;plugin&#39; + pluginName);
        if(data instanceof Count && typeof data[options] === &#39;function&#39;){
          returns = data[options].apply(data,Array.prototype.slice.call(args,1));
        }
        if(options === &#39;destory&#39;){
           $.data(this, &#39;plugin&#39; + pluginName, null);
        }
      });
       return returns !== undefined ? returns : this;
    }
    else{
      $.error(&#39;Method&#39; + options + &#39;does not exist on jQuery.CountDownF&#39;);
    }
  }
})(jQuery,window,document);

Calling method:

$(function(){
  $(".btnCur").CountDownF({
    time:120,
    countState:true,
    callback:function(){
      setTimeout(function(){
        $(".btnCur").CountDownF(&#39;clearState&#39;);
      },3000);
    }
  });
  $(".btnCur2").CountDownF({
    time:50,
    countState:true,
    cnSeconds:&#39;秒&#39;,
    callback:function(){
      setTimeout(function(){
        $(".btnCur2").CountDownF(&#39;clearState&#39;);
      },5000);
    }
  });
})

Related recommendations:

Method to implement SMS countdown of 60s

js anti-refresh countdown code js countdown code

How to implement the jQuery page countdown and refresh effect

The above is the detailed content of jQuery implementation code for countdown and SMS countdown functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function