网页倒计时网上代码很多,思路很简单,取出现在的时间跟结束时间做对比,求出时间差,然后用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()是取整数部分,因此为了更精确应该加上一秒。