练习一下-完成倒计时功能

知识点:定时器 setInterval

  • setInterval(函数,毫秒):每隔指定毫秒重复执行函数,返回定时器ID
  • clearInterval(定时器ID):停止定时器 场景:阅读协议倒计时,倒计时结束按钮启用,才可点击访问页面。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm27.aspx.cs" Inherits="WebApplication1.WebForm27" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
    <script type="text/javascript">
        var time = 5;
        var idset;

        $(function () {
            run();
            idset = setInterval(run, 1000);
        });

        function run()
        {
            if (time>0) {
                $('#but').val("请认真阅读说明(" + time + ")秒");
                time--;
            }
            else {
                $('#but').val("申请");
                $('#but').attr("disabled", false);
                clearInterval(idset);//清除定时器,停止循环
            }
        }
    </script>
</head>
<body>
    <input id="but" type="button" value="" disabled="disabled" />
</body>
</html>
Code language: HTML, XML (xml)

说明:

  1. 页面加载完成,开启定时器,1000毫秒(1秒)执行一次run()
  2. 倒计时大于0:按钮显示剩余秒数,按钮禁用
  3. 倒计时到0:按钮文字改为【申请】,解除禁用,调用clearInterval停止定时器优化:原代码把setInterval写在外面会重复启动定时器,调整放到$(function)内部。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注