• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MC_Hotdog
Yeah, you're right I'm still riding that crappy bike
博客园    首页    新随笔    联系   管理    订阅  订阅

定时器

定时器 

1.一次性定时器(可以做异步)
2.循环周期定时器(相当于时间不停的变化,可以做动画)

js和python都有垃圾回收机制:指针引用问题:当创建对象的时候指针引用自动加一,当调用一个对象或方法的时候也会自动加一,当对象调用完或者方法调用完自动减少一,当指针引用等于零的时候这些资源全部释放但是这个垃圾回收机制把定时器收不回来
开一次性定时器var timer = setTimeout(fn, 1000)
开循环定时器setInterval(fn, 1000)

清定时器clearTimeout() clearInterval()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        #box{
            width: 50px;
            height: 50px;
            background-color: blue;

        }
    </style>
</head>
<body>
    <button id="start">开启定时</button>
    <button id="clear">清除定时</button>
    <div id="box">泡起来</div>
    <script>

        // 一次性定时器
        /*
        var timer;
        document.getElementById('start').onclick = function () {
            timer = setTimeout(function () {
                console.log(1111);
            }, 3000);
                console.log(2222);
        };

        document.getElementById('clear').onclick = function () {
            clearTimeout(timer)
        };
        */

        // 循环定时器
        var count = 0;
        var timer = null;
        document.getElementById('start').onclick = function () {
            var oDiv = document.getElementById('box');
            clearInterval(timer);
            timer = setInterval(function () {
                count += 10;
                oDiv.style.marginLeft = count + 'px';
            }, 100);
        }
    </script>
</body>
</html>

  





posted @ 2019-08-13 22:43  MC_Hotdog  阅读(225)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3