Charles Tester Charles Tester - 6 months ago 41
jQuery Question

Start setInterval loop from 0

I have a slideshow in html, rotating client's ads every 10 seconds, however the first ad always display from 20 seconds. I figured that is because the setInterval starts at 10 seconds, therefore the select statement is only executed after 10 seconds and therefore the first ad's time is doubled.

I need the setInterval to start on 0 seconds.

Here is my setInterval:

<script>
setInterval(function() {
$('#slideshow > div:first')
.fadeOut(0)
.next()
.fadeIn(0)
.end()
.appendTo('#slideshow');
}, 10000);
</script>


Full code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<head>
<style>
body {
margin: 0;
}
</style>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script>
function handler() {
$('#slideshow > div:first')
.fadeOut(0)
.next()
.fadeIn(0)
.end()
.appendTo('#slideshow');
}
handler();
setInterval(handler, 10000);
</script>

</head>
<body>
<?PHP
echo "<div id='slideshow'>";
//Getting ads from the database
require_once('connect_pdo.php');
$sqlst = $conn->prepare("SELECT ads from adlist");
$sqlst->execute();
while($resultst = $sqlst -> fetch()){
$adlist = $resultst["Monday_Morning"];
echo "<div class='slideshow'>";
//Display ad as an image
//<object data='/$adlist'></object>
echo "<iframe id='frame' src='/$adlist' style='position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999; autoplay'>
Your browser doesnt support iframes
</iframe>";
echo "</div>";
}
echo "</div>";
?>

</body>

</html>

Answer

Define callback as a function and invoke it. Also pass it as first argument for setInterval

function handler() {
  alert(); //Just for demo
  $('#slideshow > div:first')
    .fadeOut(0)
    .next()
    .fadeIn(0)
    .end()
    .appendTo('#slideshow');
}
handler();
setInterval(handler, 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Comments