Reload the div via AJAX immediately and then every 5 seconds

I want to reboot divevery 5 seconds. For this, I found a script online that works. The only problem is that the first file download occurs after 5 seconds, but I want the first to be the first. This is probably a minor thing, but I have never worked with Javascript before. Thanks!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    function autoRefresh_div() {
        $("#div").load("load.html");
    }
    setInterval('autoRefresh_div()', 5000);
</script>
+4
source share
2 answers

You need to set the interval timer and then call the function directly. Try the following:

function autoRefresh_div() {
    $("#div").load("load.html");
}
setInterval(autoRefresh_div, 5000); // every 5 seconds
autoRefresh_div(); // on load

, setTimeout(), . , , , , . :

function autoRefresh_div() {
    $("#div").load("load.html", function() {
        setTimeout(autoRefresh_div, 5000);
    });
}

autoRefresh_div();
+4

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    function autoRefresh_div() {
        $("#div").load("load.html");
    }
    autoRefresh_div();
    setInterval(autoRefresh_div(), 5000);
</script>
+1

Source: https://habr.com/ru/post/1626930/


All Articles