最近要做一个网站上的活动倒计时的功能。在网上搜了一下,网上关于js倒计时的代码倒是不少,但是正正可以应用到生产环境的则是少之又少。
比如我用到的这个就是这样的:
var endDate=new Date(2014,7,25,23,59,59);
var begin = new Date();
var intDiff=Math.round((endDate.getTime()-begin)/1000);//初始日期
function timer(intDiff){
window.setInterval(function(){
var day=0,
hour=0,
minute=0,
second=0;//时间默认值
if(intDiff > 0){
day = Math.floor(intDiff / (60 * 60 * 24));
hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
}
if(day==0&&hour==0&&minute==0&&second<=0){
$("#timeshow").html("活动结束。");
}
if (minute <= 9) minute = ‘0‘ + minute;
if (second <= 9) second = ‘0‘ + second;
$(‘#day_show‘).html(day+‘天‘);
$(‘#hour_show‘).html(hour+‘小时‘);
$(‘#minute_show‘).html(minute+‘分‘);
$(‘#second_show‘).html(second+‘秒‘);
intDiff--;
}, 1000);
}
$(function(){
timer(intDiff);
});
看到了没,由于js是运行在客户端的,无法拿到服务器的时间,所以会导致“一千个读者眼里又一千个哈姆雷特”,这样是不对的,所以要获得服务器的时间。
第一想到的是用ajax请求获得服务器的时间,但是会有问题,ajax是异步请求,js执行到那一段的时候ajax还没有执行完成,所以会出现取不到值得情况。所以否决了这样的做法。
解决方法是:
<input type="hidden" id="serverTime" value="<%= request.getAttribute("time")%>"/>
在请求到这个页面之前,把时间放到atrribute里面,在页面拿到这个值,放到一个隐藏域里面。注意:定时器的代码要放到取值操作的后米阿尼,否则会出现隐藏域时空的情况。
Get!
原文地址:http://my.oschina.net/u/1455908/blog/294269