Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function on load and then every 10 minutes

Tags:

javascript

Is there a way to execute a javascript function when the page loads and then not again for another 10 minutes. Even if user browses to another page? If they dont want the function to run again until the 10 minutes is up?

like image 311
Nikon0266 Avatar asked Jun 28 '11 21:06

Nikon0266


2 Answers

Simply create the function you want to execute onload, call it once on DOM ready, and then use setTimeout()

<script type="text/javascript">
    function doSomething() {
        alert("Doing something here");
    }
    window.onload = function () {
        doSomething(); //Make sure the function fires as soon as the page is loaded
        setTimeout(doSomething, 600000); //Then set it to run again after ten minutes
    }
</script>

Edit: Didn't notice the part about even if they're on another page. If it's another page on your website, you could set a cookie once the page loads, and include a timestamp for when the cookie was set. In the window.onload of the rest of your pages, you can then read that timestamp, and calculate whether 10 minutes have passed or not. If it has, call the function again.

Edit: 10 minutes is 600000 milliseconds

like image 99
Jedediah Avatar answered Sep 19 '22 21:09

Jedediah


Even if user browses to another page?

Nope. Once your page closes, you no longer have control over what happens.

like image 42
Pekka Avatar answered Sep 19 '22 21:09

Pekka