When someone visits my site, a certain javascript function must be called. But when they refresh the page, or go to another page, this function should NOT be executed again for at least 24 hours.
Even when the web browser is closed and reopened, the function should not be executed, until it's 24 hours later.
So I was thinking of a Javascript or jQuery function that writes a cookie with a time stamp value when the function is executed.
But before the function is executed, it should check if there is a cookie.
- If it's NOT there, execute the function.
- If it's there, check the time value in the cookie and compare it with the current time.
- Is the time difference 24 hours or more, then execute the function. (and overwrite the cookie time value, for the next 24 hours)
- Is the time difference less than 24 hours, do NOT execute the function.
Would this be the right approach to achieve the goal? Or is there a built in function that does this? And could someone please help me create some javascript or jQuery code to achieve this?
Thank you.
EDIT: I found the following code here: Run code once a day:
<script type='text/javascript'>
function hasOneDayPassed() {
var date = new Date().toLocaleDateString();
if( localStorage.yourapp_date == date ) return false;
localStorage.yourapp_date = date;
return true;
}
function runOncePerDay() {
if( !hasOneDayPassed() ) return false;
alert("blabla");
}
runOncePerDay();
</script>
I tried it. The date value IS stored in local storage. But somehow the function (alert for testing purposes) is still executed when closing and reopening the web browser (while the local storage value is still there)