简体   繁体   中英

How I can display a banner that changes every 10 seconds and respect the period while the page refreshes?

I am developing a builder of advertising campaigns on js and php that displays a banner every 10 seconds with setInterval function of javascript, but when the site refreshes the setInterval restarts. if you refresh the page in less than 10 seconds it will always display the same banner.

Is there a way to maintain a setInterval function in the server side, or something?

I'm trying this with javascript storing each second on a localStorage (HTML5) to continue in the same second when you refresh the page, but I think that is not the way to do it.

I hope someone will help me to jump this hurdle that has breaking my head. :)

You need to persist the state of the interval timer somewhere, either on the server or on the client. Local storage sounds like one option. Other options would be a cookie, a url parameter, or a form parameter if you are using HTTP post.

You can store your timer in a session which will only update every ten seconds

<?php
if (!isset($_SESSION)) {
  session_start();
}
$time = time();
echo $time.'<br>';
$interval = 10; // ten seconds
if(!isset($_SESSION['timer']) || $_SESSION['timer'] == '') { // if the timer has not been started
    $_SESSION['timer'] = $time; // sets the timer to start now
    echo 'start timer = '.$_SESSION['timer'].'<br>';
} else { // the timer has already been started
    echo 'timer = '.$_SESSION['timer'].'<br>';
    if(($_SESSION['timer'] + $interval) < $time) {
        // get new banner
        echo 'get new banner<br>';
        $_SESSION['timer'] = $time; // start the timer again
    } else {
        echo 'not yet';
    }
}
?>

Try running this code and refresh the page every second... you will see "get new banner" only every ten seconds. Otherwise you will see "not yet".

You can put your code to get the new banner here `// get new banner'

Let me know if this helps.

Happy Coding !

Is there a way to maintain a setInterval function in the server side, or something?

You say you're using PHP, so just use a PHP session to record when the last banner was loaded. If you get another call and the session time is <10 seconds ago then serve the same banner, otherwise serve a new one.

Yes, you'll still need a 10 second timer in JavaScript to trigger the banner to refresh, but you don't need all that stuff with localStorage -- it sounds like you're overthinking a really simple problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM