web前端js基础之setTimeout和setinterval的使用

一、首先介绍下2者的“含义”及“区别”。

setTimeout(function(){ alert("Hello"); }, 3000); 间隔3秒弹出一次,就不再弹出了

setInterval(function(){ alert("Hello"); }, 3000);  每间隔3秒弹出一次,反复弹出

可以用来写、当前时间、进度条、切换背景、秒钟计时等等

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<style>
    #box{
        width: 100%;
        height: 40px;
        position: relative;
        background: #ddd;
    }
    #bar{
        width: 10px;
        height: 40px;
        background: #4CAF50;
        position: absolute;
    }
</style>
<body>
<input type = "submit" id="stopbtn" value="暂停"><input type = "submit" id="playbtn" value="开始"><input type="text" id="shij">
<div id="box">
    <div id="bar"></div>
</div>
</body>
</html>


<script>
    //1.秒钟计时器
    var c = 0;
    var param = 0;

    function Shij() {
        shij.value = c;
        c = c + 1;
        param = setTimeout(Shij, 1000);//变量设置全局,后面就可以进行暂停
    }
    Shij();

    stopbtn.onclick = function () {
        clearTimeout(param);//清除计时器
    }
    playbtn.onclick = function () {
        Shij();
    }
</script>


<script>
    //进度条
        var i = 0;
        function frame() {
            if (i == 100) {
                clearInterval(timenum);
            } else {
                i++;
                bar.style.width = i + '%';
            }
            shij.value = i + '%';
        }

    playbtn.onclick = function (){
        i = 0;
        timenum = setInterval(frame, 10);
    }
    stopbtn.onclick = function () {
        clearInterval(timenum);
    }
</script>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值