js代码实现计时跳转

setTimeout() 函数本身是异步的,理论上不会阻塞当前线程往下运行(这并不表示setTime() 中函数的执行不会对当前线程造成影响)。跟其并排的其他 setTimeout() 函数会异步执行,setTimeout() 中的函数会在设定好的延迟执行。

计时跳转

setTimeout(function () {
  window.location.href = "/";
},3000)

重复执行(内部setTimeout() 调用好几次,外部的setTimeout() 只调用一次。

setTimeout(function() {
   setTimeout(arguments.callee,interval);
  //需要3秒种执行一次的代码
},interval);

内部的 setTimeout() 获取当前执行的匿名函数,并每隔 interval时间,执行所在函数的代码块。3s -- 3s  --3s ....

定义一个匿名函数(实际上是一个函数表达式),并立即调用这个匿名函数。

(function () {
            if (interval > 0) {
                setTimeout(arguments.callee, 1000);
                $('em').text(interval);
                interval--;
            }

        })();

最后的代码是这个

 (function () {
            if (interval > 0) {
                setTimeout(arguments.callee, 1000);
                $('em').text(interval);
                interval--;
            } else {
                window.location.href = "/";
            }
        })();

或者多计时1秒

setTimeout(function () {
            if (interval > 0) {
                setTimeout(arguments.callee, 1000);
                $('em').text(interval);
                interval--;
            } else {
                window.location.href = "/";
            }
        }, 1000);

完整示例

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>无内容</title>
</head>
<body>
未找到结果, <span id="secound">3</span> 秒后跳转到首页
<script type="text/javascript">

    var sec = document.getElementById("secound")
    var interval = parseInt(sec.innerText);

    (function () {
        if (interval > 0) {
            setTimeout(arguments.callee, 1000);
            sec.innerText = interval;
            interval--;
        } else {
            window.location.href = "/";
        }
    })();
</script>

</body>
</html>

233

转载于:https://my.oschina.net/lemos/blog/790540

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值