Countdown and local storage - javascript

I don't know very well JavaScript but i must use it in my project.
I need countdown timers which after refresh page don't stop, not cleared and shown all time.
After press button you are redirect to other page, countown start ant button have 'disable value. After countdown time, button automatically must have enable value.
Here is my project: http://licznikii.cba.pl/dopostu/
In my first version everything works well but not after refresh page. Countdowns are cleared.
In my second version I used LocalStorage and it works well to but not much that I won't. After refresh page countowns are hidden. After countdown time button not have automatically enable value but after refreshpage. After refresh page after countdown time everything are showed good.
Please Help

After modifying your second-version it works. I've tested it in all browsers. Sorry for not code-refactoring, but I think you cope with this now :)
<!-- -------------------------------------------------------- SECOND VERSION -->
<script>
$(document).ready(function(){
$('#defaultCountdown3').countdown({until: 0, onTick: highlightLast5});
var teraz = Date.now();
var zapisanyCzas = localStorage.getItem("defaultCountdown3");
if (zapisanyCzas !== null && teraz < +zapisanyCzas) {
var restTime = secDiff(teraz, +zapisanyCzas);
console.log(restTime);
$("#YourButton3").prop('disabled',true);
$('#defaultCountdown3').removeClass('highlight').countdown('option', {until: Math.round(restTime), onExpiry: countdownFinished});
} else {
localStorage.removeItem("defaultCountdown3");
}
function highlightLast5(periods) {
if ($.countdown.periodsToSeconds(periods) === 5) {
$(this).addClass('highlight');
}
}
$('#YourButton3').click(function() {
localStorage.setItem("defaultCountdown3", Date.now() + 60 * 1000);
$('#defaultCountdown3').removeClass('highlight').countdown('option', {until: 60, onExpiry: countdownFinished});
$("#YourButton3").prop('disabled',true)
});
function countdownFinished(){
// Finished - disable your button
localStorage.removeItem("defaultCountdown3");
$("#YourButton3").prop('disabled',false)
}
function secDiff(start, end){
var diff = Math.abs(start-end);
return (diff/1000);
}
});
</script>
<script>
$(document).ready(function(){
$('#defaultCountdown4').countdown({until: 0, onTick: highlightLast5});
var teraz = Date.now();
var zapisanyCzas = localStorage.getItem("defaultCountdown4");
if (zapisanyCzas !== null && teraz < +zapisanyCzas) {
var restTime = secDiff(teraz, +zapisanyCzas);
console.log(restTime);
$("#YourButton4").prop('disabled',true);
$('#defaultCountdown4').removeClass('highlight').countdown('option', {until: Math.round(restTime), onExpiry: countdownFinished});
} else {
localStorage.removeItem("defaultCountdown4");
}
function highlightLast5(periods) {
if ($.countdown.periodsToSeconds(periods) === 5) {
$(this).addClass('highlight');
}
}
$('#YourButton4').click(function() {
localStorage.setItem("defaultCountdown4", Date.now() + 120 * 1000);
$('#defaultCountdown4').removeClass('highlight').countdown('option', {until: 120, onExpiry: countdownFinished});
$("#YourButton4").prop('disabled',true)
});
function countdownFinished(){
// Finished - disable your button
localStorage.removeItem("defaultCountdown4");
$("#YourButton4").prop('disabled',false)
}
function secDiff(start, end){
var diff = Math.abs(start-end);
return (diff/1000);
}
});
</script>

Related

how to persist an onclick function after page reload

I have an html here which executes a simple alarm based on the input time. I'm running nodejs webserver and this is my index.html
My problem is after clicking the "set alarm" button the function initiates but of course after reloading the page everything is gone. I've read about local storage but I don't know how to implement it in this scenario. I tried using garlic.js but only works on input forms like text field and checkboxes, not a button that executes a function.
var alarmSound = new Audio();
alarmSound.src = 'alarm.mp3';
var alarmTimer;
function setAlarm(button) {
var ms = document.getElementById('alarmTime').valueAsNumber;
if (isNaN(ms)) {
alert('Invalid Date');
return;
}
var alarm = new Date(ms);
var alarmTime = new Date(alarm.getUTCFullYear(), alarm.getUTCMonth(), alarm.getUTCDate(), alarm.getUTCHours(), alarm.getUTCMinutes(), alarm.getUTCSeconds());
var differenceInMs = alarmTime.getTime() - (new Date()).getTime();
if (differenceInMs < 0) {
alert('Specified time is already passed');
return;
}
alarmTimer = setTimeout(initAlarm, differenceInMs);
button.innerText = 'Cancel Alarm';
button.setAttribute('onclick', 'cancelAlarm(this);');
};
function cancelAlarm(button) {
clearTimeout(alarmTimer);
button.innerText = 'Set Alarm';
button.setAttribute('onclick', 'setAlarm(this);')
};
function initAlarm() {
alarmSound.play();
document.getElementById('alarmOptions').style.display = '';
};
function stopAlarm() {
alarmSound.pause();
alarmSound.currentTime = 0;
document.getElementById('alarmOptions').style.display = 'none';
cancelAlarm(document.getElementById('alarmButton'));
};
function snooze() {
stopAlarm();
alarmTimer = setTimeout(initAlarm, 6000); // 5 * 60 * 100
};
<input id="alarmTime" type="datetime-local">
<button onclick="alarmButton" id="setAlarm(this);">Set Alarm</button>
<div id="alarmOptions" style="display: none;">
<button onclick="snooze();">Snooze 5 minutes</button>
<button onclick="stopAlarm();">Stop Alarm</button>
</div>
Local storage would be a good way to keep track of the alarm time between sessions/page refreshes.
To save alarmTime to local storage, use:
window.localStorage.setItem('alarmTime', alarmTime)
Then when you want to use alarmTime, retrieve it from local storage with:
window.localStorage.getItem('alarmTime')
One thing to note is that local storage only stores strings, at least in the more popular browsers (see this post), so keep that in mind here.
See MDN docs on local storage for more: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
To have your function execute again after the page is refreshed, you can add a line like this:
document.onload = () => setAlarm(button);
Which will cause setAlarm to be called when the page finishes loading.
Edit
Here is a rough layout of how you can incorporate the above information into your code. I think it's actually better to store ms in local storage rather than alarmTime so that you can populate the input with ms from local storage when your document loads.
document.onload = function() {
var ms = window.localStorage.getItem('ms');
if (ms) {
populateTimeInput(ms);
var alarmButton = document.querySelector('#alarmButton');
setAlarm(alarmButton);
}
}
function populateTimeInput(newTime) {
var timeInput = document.querySelector('#alarmTime');
timeInput.value = newTime;
}
function setAlarm(button) {
var ms = document.getElementById('alarmTime').valueAsNumber;
if (isNaN(ms)) {
alert('Invalid Date');
return;
}
window.localStorage.setItem('ms', ms);
// then everything else is the same
}
function cancelAlarm(button) {
window.localStorage.clear();
// and everything else the same
}
Three main things this code adds:
When your page finishes loading, this code will check local storage for ms, if it finds a value for ms, it populates the alarmTime input with the value it's found and then calls setAlarm automatically.
When setAlarm is called, save ms to local storage (if ms has a valid value).
When cancelAlarm is called, clear local storage.
This is perhaps not the most elegant way to handle all of this, but I hope it at least gets you going in the right direction — keep iterating!
Try this, I am using setInterval instead of setTimer and I am storing the remaining time in local storage and decreasing it by 500 after every 0.5sec.
var alarmSound = new Audio();
alarmSound.src = 'alarm.mp3';
var alarmTimer;
function setAlarm(button) {
var ms = document.getElementById('alarmTime').valueAsNumber;
if (isNaN(ms)) {
alert('Invalid Date');
return;
}
var alarm = new Date(ms);
var alarmTime = new Date(alarm.getUTCFullYear(), alarm.getUTCMonth(), alarm.getUTCDate(), alarm.getUTCHours(), alarm.getUTCMinutes(), alarm.getUTCSeconds());
var differenceInMs = alarmTime.getTime() - (new Date()).getTime();
if (differenceInMs < 0) {
alert('Specified time is already passed');
return;
}
startTimer(differenceInMs)
button.innerText = 'Cancel Alarm';
button.setAttribute('onclick', 'cancelAlarm(this);');
};
function startTimer(time){
localStorage.setItem("timeLeft",time)
alarmTimer = setInterval(initAlarm, 500);
}
function cancelAlarm(button) {
clearInterval(alarmTimer);
button.innerText = 'Set Alarm';
button.setAttribute('onclick', 'setAlarm(this);')
};
function initAlarm() {
var timeLeft = parseInt(localStorage.getItem("timeLeft"))-500;
if(timeLeft <= 0){
alarmSound.play();
document.getElementById('alarmOptions').style.display = '';
} else {
localStorage.setItem("timeLeft",timeLeft)
}
};
function stopAlarm() {
alarmSound.pause();
alarmSound.currentTime = 0;
document.getElementById('alarmOptions').style.display = 'none';
cancelAlarm(document.getElementById('alarmButton'));
};
function snooze() {
stopAlarm();
alarmTimer = startTimer(6000); // 5 * 60 * 100
};
<input id="alarmTime" type="datetime-local">
<button onclick="alarmButton" id="setAlarm(this);">Set Alarm</button>
<div id="alarmOptions" style="display: none;">
<button onclick="snooze();">Snooze 5 minutes</button>
<button onclick="stopAlarm();">Stop Alarm</button>
</div>

how can i make my timer to reload to page when the countdown ends?

hello i am trying to make a countdown which refreshes the page when the countdown finished
however the timer is not refreshing page when countdown ends it start more counting in clock wise
for example the timer has to reload the page after 3 , 2 ,1 , but it goes like 3, 2, 1 , 1, 2 ,3 and so on below is my code
<?php if (isset($alert)) { ?>
<script type='text/javascript'>$('#alert').modal('show');</script>
<?php } ?>
<script type="text/javascript" src="template/js/site.js"></script>
<script type="text/javascript">
$("#DateCountdown").TimeCircles();
$("#CountDownTimer").TimeCircles({ time: { Days: { show: false }, Hours: { show: false } }});
$("#PageOpenTimer").TimeCircles();
var updateTime = function(){
var date = $("#date").val();
var time = $("#time").val();
var datetime = date + ' ' + time + ':00';
$("#DateCountdown").data('date', datetime).TimeCircles().start();
}
$("#date").change(updateTime).keyup(updateTime);
$("#time").change(updateTime).keyup(updateTime);
$(".startTimer").click(function() {
$("#CountDownTimer").TimeCircles().start();
});
$(".stopTimer").click(function() {
$("#CountDownTimer").TimeCircles().stop();
});
$(".fadeIn").click(function() {
$("#PageOpenTimer").fadeIn();
});
$(".fadeOut").click(function() {
$("#PageOpenTimer").fadeOut();
});
</script>
setTimeout(function() {
window.location.reload();
}, 1500)
Swap out the 1500 for the time in ms that you want to pass before reloading the page.
Can't see timeout/interval routines in your code, so I'll show my example to do what you want:
// your timeout in seconds
var timeSec = 10;
// fix countdown start time in seconds
var timeStart = parseInt((new Date()).getTime() / 1000);
// function to check if time is up
function TimeCheck() {
// get time left in seconds
var timeLeft = timeSec - (parseInt((new Date()).getTime() / 1000) - timeStart);
// checking if time is up
if(timeLeft > 0) {
// if time is not up yet
// ... do whatever you want to display / refresh time left to reload page ...
// set "check timeout" for next check
setTimeout(TimeCheck, 1000);
}
else {
// reload page and don't set "check timeout" again
window.location.reload();
}
}
// initial timeout start
cTimeout = setTimeout(TimeCheck, 1000);
Using setTimeout() instead of setInterval() prevents multiple instances of callback functions to stuff in execution queue.
Maybe you mean this code to solve the problem?
$("#CountDownTimer")
.TimeCircles({count_past_zero: false}) // prevent countdown below zero
.addListener(countdownComplete); // add "countdown complete listener"
function countdownComplete(unit, value, total){
if(total <= 0){
// ... make your page refresh ...
}
}

Javascript auto page refresh code

this is the code that comes in head section and it will automatically refresh the whole page in 1 min as i put 6000 in the code below
<script type="text/javascript">
setTimeout('window.location.href=window.location.href;', 6000);
</script>
is there any way for example, when there's 10 seconds left to refresh the page then, a button will display and say "Click here to reset timer" and it will reset that timer to 1 min again?
<script language="javascript">
var timeout,interval
var threshold = 15000;
var secondsleft=threshold;
startschedule();
window.onload = function()
{
startschedule();
}
function startChecking()
{
secondsleft-=1000;
if(secondsleft <= 10000)
{
document.getElementById("clickme").style.display="";
document.getElementById("timercounter").innerHTML = Math.abs((secondsleft/1000))+" secs";
}
}
function startschedule()
{
clearInterval(timeout);
clearInterval(interval);
timeout = setTimeout('window.location.href=window.location.href;', threshold);
secondsleft=threshold;
interval = setInterval(function()
{
startChecking();
},1000)
}
function resetTimer()
{
startschedule();
document.getElementById("clickme").style.display="none";
document.getElementById("timercounter").innerHTML="";
}
</script>
Please wait...<span id="timercounter"></span>
<button id="clickme" style="display:none;" onclick="javascript:resetTimer();">Click here to reset timer</button>
Assuming you have the following html for the button:
<button id="cancel-reload-button" style="display: none" onclick="cancelReload()">Cancel Reload</button>
And this as the script (Note: this gives the idea, but is not neccesarily fully tested):
// Variable for holding the reference to the current timeout
var myTimeout;
// Starts the reload, called when the page is loaded.
function startReload() {
myTimeout = setTimeout(function() {
document.getElementByID("cancel-reload-button").style.display = "inline";
myTimeout = setTimeout(function() {
window.location.reload();
} 10000)
}, 50000);
}
// Cancel the reload and start it over. Called when the button is
// clicked.
function cancelReload() {
clearTimeout(myTimeout)
startReload()
}
// On page load call this function top begin.
startReload();
I created two functions, one for starting the reload and the second one for cancelling it.
Then I assigned the timeout to the variable myTimeout which can be used to later cancel the timeout.
Then I called myTimeout twice - Once for 50 secs, at which point it shows the button and once for 10 secs after which it finally reloads.
How about below? If you click on OK to reset timer, it would keep giving the confirm box every 50 seconds. If you click cancel, it will refresh the page in 10 seconds.
setInterval(function(){ var r = confirm("Reset Timer");
if (r == true) {
setTimeout('window.location.href=window.location.href;', 60000);
} else {
setTimeout('window.location.href=window.location.href;', 10000);
}
}, 50000);
Note: In your question you specified 1 minute, but your code works for 6 seconds(6000 -- > 6 seconds not 60 seconds) I have included for a minute
You can use 2 setTimeout calls, one to make the "Reset" button show up and another one for the refresh timer reset. The trick is to store the second setTimeout on a global variable and use clearTimeout to reset it if the button is pressed.
Here is some JavaScript code to illustrate:
<script type="text/javascript">
var autoRefreshTime = 30 * 1000; // 60000ms = 60secs = 1 min
var warningTime = autoRefreshTime - (10 * 1000); // 10 secs before autoRefreshTime
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
warningTimeout = setTimeout('ShowResetButton();', warningTime);
function ShowResetButton() {
// Code to make the "Reset" button show up
}
// Make this function your button's onClick handler
function ResetAutoRefreshTimer() {
clearTimeout(waitTimeout);
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
}
</script>
The way I would do it is make a function with a timeout, and invoke that function
<script type="text/javascript">
var refreshFunc = function(){
setTimeout(function(){
var r = confirm("Do you want to reset the timer?");
if(r === false){
window.location.href=window.location.href;
}else{
refreshFunc();
}
}, 6000);
};
refreshFunc();
</script>
One big problem with using confirm in this case is you cannot program it to reject. You would have to implement you own modal/dialog box so you can auto reject in 10 seconds.
Try using setInterval():
var time;
$(function() {
time = $('#time');
$('#reset').on('click', reset);
start();
});
var timer, left;
var start = function() {
left = +(time.text()); //parsing
timer = setInterval(function() {
if (0 <= left) {
time.text(left--);
} else {
clearInterval(timer);
location.replace(location);
}
}, 1000);
};
var reset = function() {
if (timer) {
clearInterval(timer);
}
time.text('59');
start();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1><span id='time'>59</span> second(s) left</h1>
<input id='reset' value='Reset' type='button' />

Javascript Inactivity timer logic

I am trying to implement a inactivity timer using javascript
user should be shown a confirm "You are inactive for 2 min, pls click yes to continue"
If the user does not respond for 1 min the user will be redirected to some page
<script type="text/javascript">
var firstTimer = 0;
var SecondTimer = 0;
function closewindow() {
window.setInterval(ShowAlert, 1000);
}
function ShowAlert()
{
firstTimer++;
SecondTimer++;
if(firstTimer==2)
{
firstTimer=0;
confirm('Do you want to Continue');
}
}
function FinalClose()
{
window.setInterval(ShowFinalAlert, 1000);
}
function ShowFinalAlert()
{
if(SecondTimer==3)
{
window.location.href="http://www.google.com";
}
}
</script>
<body onload="closewindow();FinalClose();">
The problem with the above code is if the user does not respond to the first alert, the second timer is not firing, that is when the overall count is 3 min he should be redirected.
what is wrong with the above code.
I'll take a swing at this one
var idle_timer = 120000; // check every 2 minutes
var kick_timer = 60000; // kick user after 1 minute
var redirect = function(){
window.location = "http://google.com";
};
var idler = function(){
// start the kick timer
var kick_timer = setTimeout(redirect, kick_timer);
// prompt user to click OK
if (confirm("You get the boot in 60 seconds. Do you want the boot?")) {
clearTimeout(kick_timer);
}
else {
redirect();
}
};
//schedule idler
setInterval(idler, idle_timer);

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

Categories

Resources