I asked yesterday about saving a timer value when the browser closes and then start counting again when the user opens it. I've found that using cookies must be a good solution, so i've added the set and getcookie functions, but still i can't get my timer values. This might be easy, but i cant see what's wrong because i'm still too noob in javascript.
Does someone know what i'm doing wrong?
thank you!!
here's the code i have so far:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>Test</title>
<script type="text/javascript">
var sec = 0;
var min = 0;
var hr = 0;
var dias = 0;
var bool = true;
function stopwatch() {
sec++;
if (sec == 60) {
sec = 0;
min += 1;
}
if (min == 60) {
min = 0;
hr += 1;
}
if (hr == 24) {
hr = 0;
dias += 1;
}
totalTime = ((dias<=9) ? "0" + dias : dias) + "d, " + ((hr<=9) ? "0" + hr : hr) + " : " + ((min<=9) ? "0" + min : min) + " : " + ((sec<=9) ? "0" + sec : sec);
document.getElementById("timer").innerHTML = totalTime;
if (bool == true) {
start = setTimeout("stopwatch()", 1000);
}
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie (name) {
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
</script>
</head>
<body onload="stopwatch()">
<div id="timer" name="timer"> </div>
<button onclick="bool = false"; > pause </button>
<button onclick="bool = true;stopwatch();" > resume </button>
<form>
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie',timer.value, exp)">
</form>
<form>
<input type="button" value="Get Cookie Value" onClick="this.form.tf.value = getCookie('myCookie')">
<input type="text" name="tf" size="30">
</form>
</body>
</html>
Firstly, few issues with your code:
Strings shouldn't be used in setTimeouts
Your variables should be initialised as integers, not strings.
Back to your problem, use the unload event to save a cookie with the current time when the user closes the page. Then when the user opens the page again, detect the cookie and continue from where you left off.
If you can't figure out how to pause it, what about getting the Date when the browser closes and then getting the date when it opens again. Calculate the difference and subtract it from the value your timer is at.
I'm just throwing a general idea out there! :D
Related
I'm trying to get a simple click counter function to countdown the number of clicks users are left to use, where the number of clicks left will reset every 24 hours.
I've look through a few tutorials and implemented it visually in the alert once user has maxed the click. But how do I get about only resetting the count once the timer reaches 0.
HTML
<p><button onclick="clickCounter()" type="button">Click</button></p>
<div id="result"></div>
JavaScript
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if(Number(localStorage.clickcount) <= 0){
alert('You have max the number of connect \nTime left: '+ hours+':'+min+':'+sec);
localStorage.clickcount =4;
}
localStorage.clickcount = Number(localStorage.clickcount)-1
}
else
{
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Here's a sample of how it's running. Currently I've set it to reset right after the alert pops out, and I'm just figuring how to reset automatically when the timer is up. Thanks for any feedback and help
sample link
You can set an interval function to check the time and reset values when time is up. I've changed your code to add a interval function
checkClickCount();
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if (Number(localStorage.clickcount) < 1) {
alert('You have max the number of connect \nTime left: ' + hours + ':' + min + ':' + sec);
return;
}
localStorage.clickcount = Number(localStorage.clickcount) - 1
} else {
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
var intv = null;
function checkClickCount(){
// interval run a function in a specified period of time
intv = window.setInterval(function(){
var currentTime = new Date();
var remainDateTime = new Date();
remainDateTime.setHours(24 - currentTime.getHours());
remainDateTime.setMinutes(60 - currentTime.getMinutes());
remainDateTime.setSeconds(60 - currentTime.getSeconds());
if(localStorage.clickcount > 1){
return;
}
// If the remaining times finished, the click count will be reset
if(remainDateTime.getHours() + remainDateTime.getMinutes() + remainDateTime.getSeconds() == 0){
localStorage.clickcount = 4;
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks";
return;
}
document.getElementById("result").innerHTML = "You will get 4 more clicks in " + remainDateTime.getHours() + ":" + remainDateTime.getMinutes() + ":" + remainDateTime.getSeconds() + " later.";
}, 1000);
}
Im learning about cookies by trying to make a webshop cart.
All the products in the shop have a button that makes a cookie with a value like this:
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie','it is crunchy', exp)">
I also have a button that prints the value (it is crunchy) to a textbox (shoppinglist).
Now, I would like the cookie to be able to store several values (items from the shop).
HereĀ“s the code: (copied from a tutorial online):
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
var exp = new Date(); //set new date object
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30)); //set it 30 days ahead
function getCookie (name) {
var dc = document.cookie;
var cname = name + "=";
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
I should add that i also have another button that adds the cookie-value to a textbox, like this:
<input type="button" value="Get Cookie Value" onClick="this.form.tf.value = getCookie('myCookie')">
I have developed a JSP page. On this page, I have a count-down timer that displays time in hh:mm:ss. A link is provided to the previous page (page 2) from this page. After some work on page 2, control will be transferred to page 1 again.
I have a timer that starts when page 1 loads. When I go to page 2 and return to page 1, the timer gets refreshed. How can I make it start from where it was when I left the page?
Here's my timer code:
<script language="JavaScript">
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n ) {
return (n <= 9 ? "0" + n : n);
}
function getCurrentTime() {
time = new Date();
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
alert(hours + " " + mins + " " + secs);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if ( msLeft < 999 ) {
alert("please save your work and send your file!");
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits(secs);
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
if( hours == 0 && mins == 0 && secs == 59 ) alert("dsdsdsdsdsd");
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie ( name ) {
var cname = name + "=";
var dc = document.cookie;
if ( dc.length > 0 ) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
</script>
I think you can use cookies to store the current time and one flag=true before you switch to page 2; when you come back to page 1 you de-active flag=false to continue to calculate the time.
you can do follow steps below:
1) create a js file with content:
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
2) At form 1 before click to go to form 2, you can set the current time to cookie.
setCookie("tracking_time", time_string, 5);
Please refer Javascript Date Time functions to know how to get/set a time string
3) when come back to form 1 from form 2, you can get time value from cookie , then you set to timer to continue count time.
var time_string = getCookie("tracking_time");
Then you parse time_string to object
This is a sample complete code
<html>
<head>
</head>
<body>
<span id="countdown">Start</span>
<script>
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
var countdown = document.getElementById("countdown");
var days, hours, minutes, seconds;
var target_date = getCookie("tracking_time");
if (target_date == null) {
target_date = new Date().getTime() + (2*60*60*1000); // set countdown 2 hours
}
function updateTimer() {
setInterval(function () {
// this line below will set to function that user click on link to go to form 2
setCookie("tracking_time", target_date, 1);
// End line
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = hours + "h: " + minutes + "m: " + seconds + "s";
}, 1000);
}
updateTimer();
</script>
</body>
</html>
I have created a countdown timer function in javascript and the body tag onload event I am calling this function. But my problem is I want to display the time left thing in a label which is Child page. Is there a way to assign a control which is in child page from master page ?
Here is the function
<script type="text/javascript">
var tim;
var min = 2;
var sec = 0;
function Timer() {
if (min == 0 && sec == 0) {
clearTimeout(tim);
window.location.href = "Result.aspx";
}
else {
if (sec < 1) {
sec = 59;
if (min > 0)
min = min - 1;
}
else
sec = sec - 1;
var mins = "", secs = "";
if (min <= 9)
mins = "0" + min;
else
mins = min;
if (sec <= 9)
secs = "0" + sec;
else
secs = sec;
document.getElementById("lblTimer1").innerHTML = "Time Left : " + mins + " : " + secs;
tim = setTimeout("Timer()", 1000);
}
}
</script>
I'm calling Timer() in body onload event and lblTimer1 is the label control which is in child page.
Thanks,
Nuthan Gowda
If you are sure you won't run into conflicting ids, depending on your framework version, most simple way is setting ClientIDMode="Static" on your label. Your code should then work.
If not sure, you may set a (unique) utility cssclass of 'timerLabel' on your label, then in your function :
document.getElementsByClassName("timerLabel")[0].innerHTML = "Time Left : " + mins + " : " + secs;
I'm currently programming a calculator which is divided into two sections. The first section is a textbox which takes a string (an activity the user has entered). The second section consists of 4 textboxes. Each textbox requires a number as input. In the second section of the calculator, the calculator textboxes are labeled days, hours, minutes, and seconds. The purpose of the calculator is to determine how much money after the activity is complete. The formula for the activity & code is shown below.
MoneyMadeDuringActivity = (NumOfDays * days) + (NumOfHours * hours) + (NumOfMinutes * minutes) + (NumOfSeconds * seconds)
$(document).ready(function () {
/**
* VARIABLES
***/
var activity = $('#txtActivity').text();
var c = new Calculator();
var days = $('#txtDays').text();
var hours = $('#txtHours').text();
var minutes = $('#txtMinutes').text();
var seconds = $('#txtSeconds').text();
var MoneyMadeDuringActivity = (days * c.per_day) + (hours + c.per_hour) + (minutes * c.per_minute) + (seconds * c.per_second);
function listen(event, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else if (elem.attachEvent) {
var r = elem.attachEvent("on"+event, func);
return r;
}
}
listen("click", $("#btnCalculate"), (function() {
$("#CalcOutput").text(
"In the time it takes me to " + activity + ",<br />" + "Barack Obama makes " + "$" + MoneyMadeDuringActivity
);
});
});
My problem occurs with getting the output to work. I can't get anything to be displayed. I have the div tag with an id="CalcOutput", so I don't know why it won't display correctly. Please help.
I saw you're trying to insert html with the text method, this is wrong, you html method instead.
$("#CalcOutput").html(
"In the time it takes me to " + activity + ",<br />Barack Obama makes $" + MoneyMadeDuringActivity
);
EDIT
This way worked for me.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
//mocking up your Calculator class
function Calculator(){
this.per_day = 345665;
this.per_hour = 67845;
this.per_minute = 1234;
this.per_second = 789;
}
$(document).ready(function () {
function calculate(){
var activity = $('#txtActivity').val();
var c = new Calculator();
var days = +$('#txtDays').val();
var hours = +$('#txtHours').val();
var minutes = +$('#txtMinutes').val();
var seconds = +$('#txtSeconds').val();
var MoneyMadeDuringActivity = (days * c.per_day) + (hours + c.per_hour) + (minutes * c.per_minute) + (seconds * c.per_second);
$("#CalcOutput").html(
"In the time it takes me to " + activity + ",<br />Barack Obama makes $" + MoneyMadeDuringActivity
);
}
$("#btnCalculate").click(function() {
calculate();
});
});
</script>
</head>
<body>
activity:
<input type='text' id='txtActivity' value='foobar' /><br/>
days:
<input type='text' id='txtDays' value='3'/><br/>
hours:
<input type='text' id='txtHours' value='12'/><br/>
minutes:
<input type='text' id='txtMinutes' value='34'/><br/>
seconds:
<input type='text' id='txtSeconds' value='37' /><br/>
<button id='btnCalculate'>Calculate</button><br>
<div id="CalcOutput"></div>
</body>
</html>