JavaScript-setInterval() 定时器和setTimeout()延时器

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。

  • 从1 打印到10 每隔一秒打印一次。
	 // 定时器
            var num = 1;
            var timer = setInterval(function () {
                test.innerHTML = ++num;
                if (num == 10) {
                    //关闭定时器
                    clearInterval(timer);
                }
            }, 1000)
  • 图片自动切换
 <img id="img1" src="img/1.png" alt="">
    <div>
        <button id="btn01">开始播放</button>
        <button id="btn02">结束播放</button>
    </div>
  var img1 = document.getElementById("img1");
            var btn01 = document.getElementById("btn01");
            var btn02 = document.getElementById("btn02");
            var imgs = ["img/1.png", "img/2.png", "img/3.png", "img/4.png"];
            var index = 0;
            /*
                开启定时器    开启定时器之前为了避免用户多次点击, 可以先关闭定时器再开启
            */
            var imgTimer;
            btn01.onclick = function () {
                clearInterval(imgTimer);
                imgTimer = setInterval(function () {
                    index++;
                    if (index > imgs.length - 1) {
                        index = 0;
                    }
                    img1.src = imgs[index];

                }, 1000);
            }
            btn02.onclick = function () {
                clearInterval(imgTimer);
            }
  • 键盘上下左右控制div移动时卡顿, 用定时器来解决
	 var box = document.getElementById("box");
            var speed = 10;
            var dir = 0;
            document.onkeydown = function (e) {
                dir=e.keyCode;
            }
            document.onkeyup=function(e){
                dir=0;
            }
            setInterval(function(){
                switch (dir) {
                    case 37:
                        box.style.left = box.offsetLeft - speed + "px";
                        break;
                    case 38:
                        box.style.top = box.offsetTop - speed + "px";
                        break;
                    case 39:
                        box.style.left = box.offsetLeft + speed + "px";
                        break;
                    case 40:
                        box.style.top = box.offsetTop + speed + "px";
                        break;
                }
            },30)

setTimeout() 延时器, 函数在一段时间之后再执行。
关闭延时器 clearTimeout();

  • 页面加载5秒以后,弹出广告框
	 setTimeout(function(){
                alert("广告来了");
            },5000)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值