JS realizes a three-second countdown to jump to a new page

code show as below:

<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>

In the js code, I used the setInterval() method, which can call functions or calculation expressions in a specified period (in milliseconds).

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

This method will keep calling the function or code string until  clearInterval()  is called or the window is closed.

clearInterval() method

Can cancel the timing execution operation set by the setInterval() function

<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>

In the previous code, a stop was added.

If you only want to execute it once, use the setTimeout() method, which is the same as the setInterval() method. This is only executed once

The method of page jump:

window.location.href="/url" The current page opens the URL page    

There are many ways to jump: self.location.href="/url" The current page opens the URL page
                                        location.href="/url" The current page opens the URL page

                                        this.location.href="/url" Open the URL page on the current page parent.location.href="/url"
                                        Open the new page on the parent page
                                        top.location.href="/url" Open the new page on the top page

Original link: https://blog.csdn.net/weixin_43937528/article/details/89336188

Guess you like

Origin blog.csdn.net/z3287852/article/details/115369489