定时器

前提是你 提交于 2019-11-27 06:06:38

定时器 

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>

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!