一種網頁倒計時的實現
網頁倒計時網上代碼很多,思路很簡單,取出現在的時間跟結束時間做對比,求出時間差,然后用JS的setInterval函數來達到動態的效果。
取出當前時間時有兩種方案,如果對時間精度要求不是很高可以取客戶端時間,反之就要取服務器端時間。取服務器時間一般是用ajax獲取,我想有些朋友會在一定頻率下用ajax去服務器獲取,本人今天的一段代碼就是這樣,每隔一秒去服務器端取一次,這種方法初看沒什么問題,但在用戶量比較大和網絡狀況不好的情況下就有問題了,請求太頻繁可能會導致服務器壓力過大,反應很慢。后來在同事的提醒下代取了另一種思路,精確度基本能滿足要求。
本文提供一種比較簡單的方案,思路就是在頁面加載時用ajax去服務器獲取當前時間,然后在JS中放一個全局變量,一秒鐘加一,然后顯示時間的方法每秒鐘執行一次,執行時減去全局變量,具體代碼如下:
先建一個空白頁面(ASP.NET頁面或HTML頁面都行)用于顯示倒計時,引入jquery和一個JS文件(下面會介紹):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="JS/Test.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="auctionTime" style="font-size:40px;color:Red;"></span><br />
<span id="count"></span>
</div>
</form>
</body>
</html>
<head runat="server">
<title></title>
<script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="JS/Test.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="auctionTime" style="font-size:40px;color:Red;"></span><br />
<span id="count"></span>
</div>
</form>
</body>
</html>
再新建一個WebService(TestWS.asmx)用于獲取服務器端時間,代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Globalization;
/// <summary>
/// Get server time
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class TestWS : System.Web.Services.WebService {
public TestWS () {
}
[WebMethod]
public string GetServerTime()
{
return DateTime.Now.AddSeconds(120).ToString("MMM dd,yyyy HH:mm:ss", CultureInfo.GetCultureInfo("en-US"));
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Globalization;
/// <summary>
/// Get server time
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class TestWS : System.Web.Services.WebService {
public TestWS () {
}
[WebMethod]
public string GetServerTime()
{
return DateTime.Now.AddSeconds(120).ToString("MMM dd,yyyy HH:mm:ss", CultureInfo.GetCultureInfo("en-US"));
}
}
然后就是JS調用這個WebService獲取服務器端時間了,JS(Test.js)代碼如下:
var endTime="Dec,27,2010 23:06:00";
$(function () {
GetServerTime();
})
function GetServerTime() {
$.ajax({
url: '/UI/WS/TestWS.asmx/GetServerTime',
data: '{}',
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
serverTime=data.d;
$("#count").text(count);
show_time();
setInterval("show_time()", 1000);
},
error: function (xhr) {
alert(xhr);
}
});
}
var serverTime;
$(function () {
GetServerTime();
})
function GetServerTime() {
$.ajax({
url: '/UI/WS/TestWS.asmx/GetServerTime',
data: '{}',
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
serverTime=data.d;
$("#count").text(count);
show_time();
setInterval("show_time()", 1000);
},
error: function (xhr) {
alert(xhr);
}
});
}
var serverTime;
var timespan = 0;
function show_time() {
var time_distance, str_time;
var int_day, int_hour, int_minute, int_second;
var time_now = new Date(serverTime);
var time_end = new Date($("#endTime").text());
time_now = time_now.getTime();
time_end = time_end.getTime();
//取系統現在時間
time_distance = time_end - time_now-timespan*1000;
//時間間隔。
if (time_distance >= 0) {
timespan = timespan + 1;
if (Math.floor(time_distance) < 30000) {
$("#auctionTime").css("color", "#FF0000");
}
if (time_distance == 0) {
if (toop) {
toop = false;
$("#auctionTime").css("color", "#369A28");
$("#currTime").text("00:00:00");
$("#auctionTime").text("00:00:00");
GetWiner();
return;
}
return;
}
//取出間隔時間的天、小時、分
int_day = Math.floor(time_distance / 86400000);
time_distance -= int_day * 86400000;
int_hour = Math.floor(time_distance / 3600000);
time_distance -= int_hour * 3600000;
int_minute = Math.floor(time_distance / 60000);
time_distance -= int_minute * 60000;
int_second = Math.floor(time_distance / 1000);
if (int_hour < 10)
int_hour = "0" + int_hour;
if (int_minute < 10)
int_minute = "0" + int_minute;
if (int_second < 10)
int_second = "0" + int_second;
str_time = int_hour + ":" + int_minute + ":" + int_second;
$("#auctionTime").text(str_time);
} else { }
}
function show_time() {
var time_distance, str_time;
var int_day, int_hour, int_minute, int_second;
var time_now = new Date(serverTime);
var time_end = new Date($("#endTime").text());
time_now = time_now.getTime();
time_end = time_end.getTime();
//取系統現在時間
time_distance = time_end - time_now-timespan*1000;
//時間間隔。
if (time_distance >= 0) {
timespan = timespan + 1;
if (Math.floor(time_distance) < 30000) {
$("#auctionTime").css("color", "#FF0000");
}
if (time_distance == 0) {
if (toop) {
toop = false;
$("#auctionTime").css("color", "#369A28");
$("#currTime").text("00:00:00");
$("#auctionTime").text("00:00:00");
GetWiner();
return;
}
return;
}
//取出間隔時間的天、小時、分
int_day = Math.floor(time_distance / 86400000);
time_distance -= int_day * 86400000;
int_hour = Math.floor(time_distance / 3600000);
time_distance -= int_hour * 3600000;
int_minute = Math.floor(time_distance / 60000);
time_distance -= int_minute * 60000;
int_second = Math.floor(time_distance / 1000);
if (int_hour < 10)
int_hour = "0" + int_hour;
if (int_minute < 10)
int_minute = "0" + int_minute;
if (int_second < 10)
int_second = "0" + int_second;
str_time = int_hour + ":" + int_minute + ":" + int_second;
$("#auctionTime").text(str_time);
} else { }
}
代碼很簡單,結構就不說了,只是注意WebService的路徑,效果如下:

只是我在服務器端把當前時間添加了120秒,但在這兒時間差確是119,寫到這兒我查了一下,是Math.floor()精度原因,Math.floor()是取整數部分,因此為了更精確應該加上一秒。

浙公網安備 33010602011771號