定时器

原生的JS使用计时器做出图片轮播的效果。

window提供的定时器可以分为两种:setTimeout(code, time)和setInterval(code, time)

(一)setTimeout(code, time)

<script type="text/javascript">
    function test(){
        alert("这是一个测试数据!");
    }
    //如果是setTimeout(test(),5000);则会立即执行!即使是匿名函数也会立即执行!
    window.onload = function(){
        setTimeout(alert("123"),5000);
    };
    //setTimeout(test(),5000);
    // setTimeout(test,5000);        
</script>

注意:计时器中的内容只会执行一次,可以使用clearTimeout( obj )销毁。

function test(){
        alert("这是一个测试数据!");
    };
    st = setTimeout(test,5000);    
    clearTimeout(st);

上述的代码,不会有弹窗出来,因为还没有弹出就已经被销毁了。

(2)setInterval()循环计时器

//5秒之后关闭这个循环计时器
    stI = setInterval(function(){
        console.log(1);
    },1000);
    setTimeout(function(){
        clearInterval(stI);
    },5000);

 

 

 

关于var全局变量

var arr = [1,2,3,4];
    for(var i=0; i< arr.length; i++){
        setTimeout(function(){
            console.log(arr[i]);
        },1000);
    };
    console.log(i);
    //返回值是i=4;console.log()的输出值全部都是undefined

怎么解决呢?使用let 模块变量

    var arr = [1,2,3,4];
    for(let i=0; i< arr.length; i++){
        setTimeout(function(){
            console.log(arr[i]);
        },1000);
    };

 案例一:新年计时器,倒计时10秒钟,然后打出新年好!

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>新年倒计时</title>
    <style type="text/css">
        .wrap{width:1200px; margin:0 auto; -border:1px solid red; }
        .time_show{display: block; width:60%; margin:100px auto; color: red; font-size: 100px; height: 300px; line-height: 300px; font-weight: bold; -border:1px solid red;}
        
    </style>
</head>
<body>
    <div class="wrap">
        <span class="time_show"></span>
    </div>
    <script type="text/javascript">
        var dateTime = 10; 
        function daojishi(){
            var time_show = document.getElementsByClassName('time_show')[0];
            time_show.innerHTML = "倒计时 " + dateTime + " 秒!";
            dateTime--; 
            if(dateTime == -1){
                time_show.innerHTML = '新年好!';
                clearInterval(xinnian);
            };
        };
        xinnian = setInterval(function(){
            daojishi();
        },1000);
    </script>
</body>
</html>

 

 

 

posted @ 2019-11-04 21:07  壹碗  阅读(165)  评论(0编辑  收藏  举报