Reputation: 97
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.
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)
Upvotes: 1
Views: 1214
Reputation: 10627
You might consider doing something like:
function oncePerDay(func){
let dt = new Date, tm = dt.getTime();
if(localStorage.timestamp){
if(tm-localStorage.timestamp > 86399999){
localStorage.timestamp = tm; func(tm);
}
}
else{
localStorage.timestamp = tm; func(tm);
}
}
addEventListener('load', ()=>{
oncePerDay(tm=>{
console.log(tm);
});
});
Of course, if the Client is on the Browser for over 24 hours this won't work without an interval to check for the time change.
Upvotes: 1
Reputation: 497
using cookies or local storage would work, but someone could easily just clear their cookies/local storage or edit the client side code. So if it's really important that they can't re-run the function then you might want to look into storing this information on the server
Upvotes: 2