JS实现倒计时三秒钟跳转到新的页面

代码如下:

<div id="box">
    <p>页面在
    <span id="Os">5</span>
     s后跳转
    </p>
</div>
<script>
    var Os=document.getElementById("Os");
    var num=5;
    var timer=setInterval(function () {
        num--;
        Os.innerText=num;
        if(num==0){
            window.location.href="https://www.baidu.com/";
        }
    },1000)
</script>

在js代码里,我用了setInterval() 方法,此方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval(code, milliseconds);        (code是一个代码串,milliseconds(时间),多少时间调用一次)
setInterval(function, milliseconds, param1, param2, ...)  (param是传给执行函数的其他参数,根据情况写)

这个方法对函数或代码串会一直调用,直到 clearInterval() 被调用或窗口被关闭。

clearInterval() 方法

可取消由 setInterval() 函数设定的定时执行操作

<div id="box">
    <p>页面在
    <span id="Os">5</span>
     s后跳转
    </p>
    <button id="btn" onclick="stop()">停止</button>
</div>
<script>
    var Os=document.getElementById("Os");
    var num=5;
    var timer=setInterval(function () {
        num--;
        Os.innerText=num;
        if(num==0){
            window.location.href="https://www.baidu.com/";
        }
    },1000)
    function stop() {
        clearInterval(timer);
    }
</script>

上个代码,加了个停止。

若你只想执行一次那就用,setTimeout() 方法,和setInterval() 方法使用方法一样,这个只执行一次

页面跳转的方法:

window.location.href="/url" 当前页面打开URL页面    

还有好多种跳转的方法:self.location.href="/url" 当前页面打开URL页面
                                        location.href="/url" 当前页面打开URL页面

                                        this.location.href="/url" 当前页面打开URL页面
                                        parent.location.href="/url" 在父页面打开新页面
                                        top.location.href="/url" 在顶层页面打开新页面

原文链接:https://blog.csdn.net/weixin_43937528/article/details/89336188

猜你喜欢

转载自blog.csdn.net/z3287852/article/details/115369489