1. 程式人生 > >js 倒計時外掛(伺服器時間,終端時間供選擇)

js 倒計時外掛(伺服器時間,終端時間供選擇)

;
(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; }());