倒计时显示与控制

在前台功能开发的过程中可能会遇到这种情况:

多个订单商品的列表,点击查看详情,里面有对应的商品活动时间的倒计时,如果点击查看不是刷新整个页面的话,需要在查看详情返回列表时将倒计时关闭掉。否则就会出现如下这种情况:

多个倒计时同时运行,导致页面显示出错。

简单模拟类似情形,做了一个简单的活动剩余时间页面:

其中“停止”按钮可以代替商品详情里的返回按钮,点击“停止”后:

关闭了倒计时,活动剩余时间不再刷新。

在点击“继续”按钮后:

重新启动倒计时,显示最新剩余时间。

完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="GBK">
    <title>倒计时显示</title>
    <script src="https://g.alicdn.com/kissy/k/1.4.8/seed-min.js"></script>
    <script type="text/javascript">
        KISSY.use("dom,io,event",function(S,DOM,IO,Event){
            var endDate = new Date("2018-07-31 16:46:00");//活动结束时间,可自行传入
            var timer;
            timer = setInterval(function(){getCountTime(endDate);},1000);
            function getCountTime(endDate) {
                var nowDate = new Date();
                var nowTime = nowDate.getTime();
                var endTime = endDate.getTime();
                var diffTime = endTime-nowTime;
                var day,hour,minute,second;
                if (diffTime>0) {
                    day = Math.floor(diffTime/1000/60/60/24); //天
                    hour = Math.floor(diffTime/1000/60/60%24); //小时
                    minute = Math.floor(diffTime/1000/60%60);  //分钟
                    second = Math.floor(diffTime/1000%60);   //秒  
                    console.log("day="+day+",hour="+hour
                    +",minute="+minute+",second="+second);

                    DOM.html("#day",day+"天");
                    DOM.html("#hour",hour+"小时");
                    DOM.html("#minute",minute+"分钟");
                    DOM.html("#second",second+"秒");
                }else{//停计时器
                    clearInterval(timer);
                }
            }
            //浏览器停止倒计时
            Event.on('#stop','click',function(){
                console.log("停止");
                clearInterval(timer);
            });
            //浏览器继续倒计时
            Event.on('#continue','click',function(){
                console.log("继续");
                timer = setInterval(function(){getCountTime(endDate);},1000);
            });
        });
    </script>
</head >
<body>
    <div>
    	<span>距离活动结束时间剩余:</span>
        <span id="day">0天 </span>
        <span id="hour">0小时 </span>
        <span id="minute">0分钟 </span>
        <span id="second">0秒 </span>
    </div>
    <button type="button" id="stop">停止 </button>
    <button type="button" id="continue">继续</button>
</body>
</html>

如有错误之处,欢迎指出,万分感谢!

猜你喜欢

转载自blog.csdn.net/Denglishang/article/details/81287295
今日推荐