js定时器

window 中的定时器

                            1、定时器分类

                                   1、周期性定时器【广告】

                                          每间隔一定的时间后,就执行一遍指定程序,反复执行

                                   2、一次性定时器

                                          在指定的时间间隔之后,只执行一次操作

                            2、周期性定时器

                                   1、声明定时器

                                          var ret = setInterval(fun,time);

                                          fun:要周期性执行的操作,可以是匿名函数

                                          time:时间间隔周期,以毫秒为单位

                                          ret:返回已创建好的定时器对象

                                   2、清除定时器

                                          clearInterval(timer)

                                          timer:创建好的,要停止的定时器对象

 

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
 </head>
 <body>
  <script>
      var timer ; //全局的定时器对象
      function testInterval(){
         timer = setInterval(function(){
            var now = new Date();
            console.log(now.toLocaleString());
         },1000);
      }

      function stopInterval(){
         clearInterval(timer);
      }
   </script>
   <button onclick="testInterval()">开始</button>
   <button onclick="stopInterval()">停止</button>
 </body>
</html>

3、一次性定时器

                                   1、声明一次性定时器

                                          var ret = setTimeout(fun,time);

                                          fun:指定时间间隔后要执行的操作

                                          time:时间间隔

                                          ret:返回已启动的定时器对象

                                   2、清除定时器

                                          clearTimeout(timer);

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
 </head>
 <body>
  <script>
      var timer = null ; //全局定时器变量
      function closeWindow(){
         if(confirm("确认关闭网页吗?")){
            timer = setTimeout(function(){
               window.close();
            },5000);
         }
      }

      function cancelClose(){
         if(timer != null){
            clearTimeout(timer);
            alert("取消成功!");
         }
      }
   </script>
   <button onclick="closeWindow()">关闭网页</button>
   <button onclick="cancelClose()">取消关闭</button>
 </body>
</html>

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值