how to refresh the page after a few seconds

This tutorial explains how to refresh the page after a few seconds each time (certain interval time).

Sometime we need to redirect the page to another one after 3 seconds.So we need to refresh the page.

we has two methods to refresh the page in a certian interval.

use window.setInterval() or windows.setTimeout()


method 1:Sample code using setTimeout

<div onClick="autoRefresh(3000)">Refresh page after 3 seconds</div>
<script>
function autoRefresh(timeToRefresh) {
    setTimeout("location.reload(true);",timeToRefresh);
}
</script>


method 2:Sample code using setInterval

<div>
    <input type="button" value="Start Fresh" onClick="Update();" />
    <input type="button" value="Stop Fresh" onClick="Stopupdate();" />
    <span>Content will be refreshed after </span>
    <span id="showtime" color="red"></span><span>second</span>
    <input type="button" value="Check Now" onClick="sendRequest();" />
</div>
<div id="container"></div>


<script type="text/javascript" language="javascript">
    var timeout = null; //setInterval handle
    var xmlHttp = false;
    //initialize XMLHttpRequest object
    function createXmlHttp() {
        xmlHttp = false;
        if (window.ActiveXObject) {
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
    }
    var intervatime = 10; //10 second
    var lefttime = intervatime;
    // use timestamp for no cache in browser
    function sendRequest() {
        createXmlHttp();
        //get response from remote.php
        var url = "remote.php?timestamp=" + new Date().getTime();
        if (!xmlHttp) {
            alert("XMLHttpRequest is not Create!");
        }
        xmlHttp.open("GET", url, true);
        xmlHttp.onReadystatechange = function () {
            var tag = document.getElementById("container");
            tag.innerHTML = "";
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                tag.innerHTML = xmlHttp.responseText;
            }
        }
        xmlHttp.send(null);
    }
    function Show() {
        var showspan = document.getElementById("showtime");
        showspan.innerHTML = lefttime;
        lefttime--;
        if (lefttime == 0) {
            sendRequest();
            lefttime = intervatime;
        }
    }
    //start
    function Update() {
        timeout = window.setInterval("Show()", 1000);//refresh the notice text every second.
    }
    //stop
    function Stopupdate() {
        if (timeout != null) {
            window.clearInterval(timeout);
        }
    }
</script>


date2019-03-23 11:31:48 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *