JavaScript定时器的简单小案例

  1. 定时器

    			setInterval(function(){
    			},t)
    		每隔t ms执行一次。***要注意,循环执行的***
    
  2. 清除定时器
    上面说了,定时器是循环执行的,有些情况下,我们不想它循环执行,所以就必须来清除定时器。
    清除定时器可以用延时器来完成。

clearInterval(定时器名称);

举一个简单的例子

let sum = setInterval(function(){
	console.log(x);
},100);

let x=9;
steTimeout(function(){
	clearInterval(sum);
},300)

上面代码在打印出3次9后就会停止打印
在这里插入图片描述
3、关于定时器的一个小小案例(让一个小圆绕着大圆做圆周运动)

		代码部分
<style>
    body{
        margin: 0;
    }
    .round{
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 400px;
        height: 400px;
        border:1px solid red;
        border-radius: 50%;
        margin:100px auto 0;
    }
    .point{
        width: 10px;
        height: 10px;
        border:1px solid blue;
        border-radius: 50%;
        background-color: blue;
    }
</style>
<body>
    <div class="round"> 
        <div class="point"></div>
    </div>
    <script>
        let oPoint=document.querySelector(".point");
        let STEP=Math.PI/60;
        let cow=0;

        setInterval(function(){
            oPoint.style.transform="translate("+200*Math.sin(cow)+"px,"+200*Math.cos(cow)+"px)";
            cow+=STEP;
        },1000/60)
    </script>

结果部分

在这里插入图片描述
由于我在这插入了一张静态的图片,可能看不出小圆绕着大圆做圆周运动。但它确实是在做圆周运动。

发布了1 篇原创文章 · 获赞 4 · 访问量 34

猜你喜欢

转载自blog.csdn.net/HeartzzZZ/article/details/105059148
今日推荐