Serge Serge - 6 months ago 45
Ajax Question

Jquery image load interval

This script from source rotates images defined in AJAX.PHP with interval 2000 ms (2 seconds)

But the problem is that a first image also loads not immediately on page load, but after 2 seconds.

QUESTION - is it possible to correct the code below to show any first image immediately on page load ? - and after that rotate other images as defined, with 2 seconds interval.

<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$("document").ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"ajax.php",
success:function(result){
$("#banner_div").html(result);
}
});
}, 2000);
});
</script>
</head>
<body>
<div id="banner_div"></div>
</body>


Thanks in advance for any hints to try,

Answer

You can make it a function and call it in the interval + also on page load:

<script>
$("document").ready(function(){
    function loadImage(){
        $.ajax({
            type:"POST",
            url:"ajax.php",
            success:function(result){
                $("#banner_div").html(result);
            }
        });
    }
    setInterval(loadImage, 2000);
    loadImage();
});
</script>