setInterval 定时器的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>setInterval方法的使用</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            background-color: red;
            position: absolute;
            top:50px;
        }
    </style>
</head>
<body>
<button>点我</button>
<div></div>
<script>
    function $(selector){
        return document.querySelector(selector);
    }
    var num = 0;
    $('button').onclick = function(){
        //开启定时器,占内存
        var Timer = setInterval(function(){
            if (num > 600){
                //停止定时器
                clearInterval(Timer)
            }
            num += 20;
            $('div').style.left = num + 'px';
        },100);
    };
</script>
</body>
</html>

 

posted on 2019-07-08 17:02  lilyxiaoyy  阅读(1163)  评论(0编辑  收藏  举报

返回
顶部