; (function(){ 'use strict'; var timer = function (params) { if (!(this instanceof timer)) return new timer(params); var defaults = { //结束时间 毫秒 endTimeMill: 0, //剩余时间 timeLeftMill: 0, //毫秒 speedMill: 1000, //服务器时间 serverTime:false, //延时时长毫秒 delayTimeMill:3000, //时间展示 showTime:undefined } var t = this; t.params = params || {}; for (var def in defaults) { if (typeof t.params[def] === 'undefined') { t.params[def] = defaults[def]; } } t.showTime = function(timeLeftMill){}; /** 定时任务开始 */ t.start = function(){ if (t.params.serverTime) { t.requestServerTime(); } else { t.params.timeLeftMill = t.params.endTimeMill - (new Date().getTime()); t.startCounting(); } }; //设置自定义值 t.requestServerTime = function(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new window.XMLHttpRequest(); }else{ // ie xhr = new ActiveObject("Microsoft") } xhr.open("GET",location.href,true); xhr.send(null); xhr.onreadystatechange=function(){ if (xhr.status == 200) { if(xhr.readyState == 2){ var time = xhr.getResponseHeader("Date"); var serverTimeMill = new Date(time).getTime(); t.params.timeLeftMill = t.params.endTimeMill - serverTimeMill; t.startCounting(); } } else { t.params.timeLeftMill = t.params.endTimeMill - (new Date().getTime()); t.startCounting(); } } }; //绑定事件 t.startCounting = function(){ t.params.timeLeftMill -= t.params.speedMill; if(t.params.timeLeftMill > 0){ if(t.params.showTime) { t.params.showTime.call(this, t.params.timeLeftMill); } setTimeout(function(){ t.startCounting(); },t.params.speedMill); }else{ if(t.params.showTime) { t.params.showTime.call(this, 0); } } }; //提供API给外部使用 return { start:t.start,//设置值 }; }; window.timer = timer; }());