几种js 方法实现倒计时

一、用js  setInterval  实现,每间隔一秒调用一次倒计时函数,在函数里面设置为0 时,取消定时器javascript

 <body>
倒计时<span id="time"></span>

<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var i=9;
var interval=setInterval(function(){
$("#time").html(i);
i--;
if(i<0){
clearInterval(interval);
};

},1000);

});
//总结:$("#time").html(i);  为元素赋值
</script>


</body>

二、用 js  setTimeout 实现,原理是间隔一秒调用自身,直到倒计时为0时,处理其余业务逻辑html

<button id="btn" onclick="settime(this)">点击</button>
<script type="text/javascript"> 
function settime(val) { 
	if (countdown == 0) { 
		val.removeAttribute("disabled"); 
		val.innerHTML="免费获取验证码"; 
		countdown = 60; 
	} else { 
		val.setAttribute("disabled", true); 
		val.innerHTML="从新发送(" + countdown + ")"; 
		countdown--; 
	} 
	setTimeout(function() {settime(val)},1000) 
} 
</script>

三、用jquery  setInterval  实现倒计时java

<div class="state state1">
		<span id="content" class="orange">10 </span>秒后从新关闭
</div>
<div class="outbuttonDiv">
		<button class="btn-primary" id="buttonClose" >阀门关闭</button>
</div>

<script type="text/javascript">
		$(function () {
            $('#buttonClose').click(function () {
                var count = 10;
                var countdown = setInterval(CountDown, 1000);
                function CountDown() {
                    $("#buttonClose").attr("disabled", true);
                    $("#content").html(count+" ");
                    if (count == 0) {
					   $(".state1").addClass("green").html("关闭成功");
					   //$(".state1").addClass("red").html("关闭失败");
					   //$(".state1").addClass("green");
                       //$("#buttonClose").removeAttr("disabled");
                        clearInterval(countdown);
						
                    }
                    count--;
                }
            })
		})
</script>

四、用jquery setTimeout 实现倒计时jquery

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script type="text/javascript" src="js/jquery.js"></script>
</head>

<body>
    <input type="button" id="btn" value="免费获取验证码" />
    <span id="content">10</span>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $("#btn").click(function(){
            var countdown = 10;
            setTimeout(
            function settime() {
                if (countdown < 0) {
                	clearTimeout(a)
                	$("#content").html("finished");
                    //countdown = 60;
                } else {
                    $("#content").html(countdown);
                    countdown--;
                }
                var a = setTimeout(settime, 1000)
            },0)
        }) 
    })
    </script>
</body>
相关文章
相关标签/搜索