Home  >  Article  >  Web Front-end  >  jquery implements a global timer instance sharing

jquery implements a global timer instance sharing

小云云
小云云Original
2018-01-06 09:37:391479browse

This article mainly introduces jquery to implement a global timer, which can be used in shopping malls. I hope it can help everyone.

The example of this article shares with you the jquery global timer that can be used in shopping malls for your reference. The specific content is as follows

Implementation ideas

Traverse all elements to be timed , add a setInterval timing function to perform update timing operations every X seconds (there may be formatting time operations in the middle).

Code implementation

ps: JQ elements will be converted into DOM elements when the value is obtained through arr[i]. Use $(arr[i]) to convert between dom elements and JQ

Get all the elements to be timed

var arrList =$(".stime");
setInterval(function(){
 //遍历数组
 for(var i = 0,l = arrList.length; i<l ;i++ ){
  var elem = arrList[i];
  //格式化时间插入HTML文档
  $(elem).html(DateDiff( new Date(), new Date($(elem).attr("time") ), elem ));
 }
},1000);

Calculate the time function, which can be reversed or correct

ps: If it is the time passed from the Java background, pay attention to the time format, which has been processed here (It’s a pitfall);

/*DateDiff 处理*/
function DateDiff(t1, t2, elem){
 //GTM CST 时间相差14小时 
 var diff = t1.setHours(t1.getHours()+14) - Date.parse(t2);
 //超过一天显示warning色
 if(diff>(1000*60*60*24)){
  $(elem).css({color:"rgb(247, 186, 42)"});
 }
 return ShowTime(diff);
}

Display processing function, you can choose the accuracy

No need, just comment it out

/*fuc 计时显示处理*/
function ShowTime(ms){
 var obj = {
  "天" : 1000*60*60*24,
  "时" : 1000*60*60,
  "分" : 1000*60
  /*
  "秒" : 1000
  */
 };
 var tmp = ms;
 var str = "";
 for( var i in obj ){
  //向下取整 1.5天 => 1天
  s = Math.floor( tmp / obj[i] );
  tmp = tmp % obj[i];
  str += s+i;
 }
 return str;
}

Related recommendations:

Implementation of jQuery timer function and countdown function

JavaScript minute and second countdown timer implementation method

javascript timer implementation

The above is the detailed content of jquery implements a global timer instance sharing. 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