js setInterval定时器

落花浮王杯 提交于 2020-02-02 01:18:43

setInterval():定时器

回去重复执行某一功能
参数1:每次执行的具体任务,自定义
参数2:每次执行的间隔时间,单位毫秒
setTimeout():只执行一次的定时器
参数1:执行的具体时间,
参数2:间隔多久(延迟多久)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    
    .box{
        width: 200px;
        height: 200px;
        background-color: pink;
        line-height: 200px;
        text-align: center;
        font-size: 30px;
    }
    </style>
</head>
<body>
    <div class="box"></div>
    
    <script>
        box=document.getElementsByClassName("box")[0];
        box.innerHTML = Math.floor(Math.random()*250);
        console.log(box)
        var s = 0;
        var num = 0;
        var time =setInterval(function(){ //参数1:功能自定义
            s = Math.floor(Math.random()*250);
            box.innerHTML = s;
            num++;                   //变量自增
            if(num>6){               //判断是否达到指定条件
                clearInterval(time); //清除定时器
                time = null          //置空
            }
        //清除定时器:
		//    需要有记录器(变量自增),来记录运行次数,到达指定条件时触发
		//    定义定时器时,需要定义变量来保存这个定时器(例如: time)
		//	  然后使用clearInterval()方法。来清除这个变量中的定时器,并将这个变量 置空(time = null)    
        },1000) //参数2:间隔的时间
        
        var time_two = setTimeout(function(){
            box.style.backgroundColor = "red";
            
        },2500)
        
    </script>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!