Reputation: 1951
Just wondering if there is a simple way to have an alert that can't fire more then once in a certain time period. All I'm using is
alert(test)
I just don't want users to see this alert more then once in a 4 hour period.
Upvotes: 0
Views: 390
Reputation: 707806
var lastShown = new Date(1900, 1, 1); // initialize
function showMsg(msg) {
var minTime = 4 * 60 * 60 * 1000; // 4 hrs seconds (set this to however long you want)
var now = Date.now();
if (now - lastShown < minTime) return; // just return if not enough time has elapsed
lastShown = now;
alert(msg);
}
Working example here: http://jsfiddle.net/jfriend00/xUWf5/
Upvotes: 0
Reputation: 66
You'd have to make a function to test that kind of thing. Something along the lines of this would work:
You could call alertLimited(test) all you want, but it would only actually call alert() a minimum of once every 4 hours.
var alertLimited = function () {
var lastAlertTime = 0;
return function alertLimited(input) {
var current = new Date();
current.setHours(current.getHours() - 4);
if ((current - lastAlertTime) > 0) {
lastAlertTime = new Date();
alert(input);
}
};
}();
Upvotes: 0
Reputation: 154908
Keep track of when you alert and save that on the client's computer:
function doAlert(text) {
if(!localStorage['last_alert'] || new Date - localStorage['last_alert'] > 4 * 60 * 60 * 1000) {
localStorage['last_alert'] = +new Date;
alert(text);
}
}
And use doAlert
instead of alert
, which now delegates alerts.
Upvotes: 0
Reputation: 169471
(function() {
var _alert = window.alert,
queue = [];
window.alert = function(msg) {
queue.push(msg);
}
setInterval(function() {
if (queue.length !== 0) {
_alert(queue.pop());
}
}, 1000 * 60 * 4);
})();
You may want to implement the effect of calling it more then once every 4 hours differently.
Upvotes: 1
Reputation: 3885
One way to do this would be to store the timestamp of when the first alert happened in a cookie, and then next time when you get to the point where you need to call the alert again load the cookie (if its there, if it isn't alert) and check if the time is greater then 4 hours since the last time and if so alert again otherwise don't
Upvotes: 0