定时器

运动

标签(空格分隔): 运动


定时器分为两种
  • 重复型定时器: 以指定的时间间隔,做同一件事,只要不停止,一直做下去。
  • 延迟型定时器: 在指定的时间间隔后,做一件事,只做一次。
重复型定时器 setInterval
  • setInterval(fn, delay, arg1, arg2…)
  • fn: 要做的事情
  • delay: 时间间隔(单位:ms) 1s === 1000ms
  • arg1, arg2…: 如果fn有参数,那么这些代表fn的参数
  • 返回值:当前定时器的编号(不同的浏览器这个编号是不一样的)
  • html5的最新规范,规定了定时器最短的时间间隔是4ms
 setInterval(function() {
   console.log(1);
 }, 1000);

function fn(n){
      // console.log(n);
    }

var t1 = setInterval(fn, 1000, 1);
var t2 = setInterval('fn(1)', 1000);
var t3 = setInterval('fn(1)', 1000);
var t4 = setInterval('fn(1)', 1000);    

console.log(t1, t2, t3, t4);   //t1, t2, t3, t4  代表的是定时器的编号
延迟型定时器
  • setTimeout(fn, delay, arg1, arg2…)
  • 参数和setInterval是一样的返回值也是当前这个定时器的编号
   // function fn(){
    //   alert('hello!');
    // }
    // 
    // setTimeout(fn, 3000);

    // -------------------------------------------
     (function fn(){
       console.log('xxxx');
       console.log(setTimeout(fn, 1000));
     })();
清除定时器


  • clearInterval(要清除的定时器的编号)
  • clearTimeout(要清除的定时器的编号)

这2个方法的参数,无论你给它们什么样的数据类型,都不会报错。
    // var n = 1;
    // var t1 = setInterval(function() {
    //   console.log(n++);
    //   
    //   if(n > 50){
    //     // clearInterval(t1);
    //     clearTimeout(t1);
    //   }
    // }, 50);

    // var t2 = setTimeout(function() {
    //   alert('hello')
    // }, 3000);
    // 
    // document.onclick = function (){
    //   clearTimeout(t2);
    // };


    // -----------------------------
    // clearTimeout(null);
    // clearTimeout(undefined);
    // clearTimeout(function(){});
案例  0926 实例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值