A single cookie timer (meaning value) is an idea without a hitch, I want it to pause after 1 hour and start doing what it means after clicking on a motion.
Google didn't help. https://jsfiddle.net/m6vqyeu8/
Please share your version or help wrote your own.
<!doctype html>
<html>
<head>
<title>timer</title>
<meta charset=utf-8>
</head>
<script>
let initialValue = 0.50000096;
let multiplier = 0.00000001;
let getCookie = (c_name) => {
let i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
let setCookie = (c_name, value, exdays) => {
let exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
let c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
let lastUpdated = getCookie('lastUpdated') * 1;
if (!lastUpdated) {
lastUpdated = Date.now();
setCookie('lastUpdated', lastUpdated, 9999);
}
let diff = (Date.now() - lastUpdated) / 1000;
let cu = (diff * multiplier) + initialValue;
let doCu = () => {
document.getElementById('cu').innerHTML = cu.toFixed(8);
cu = cu + multiplier;
}
document.write("<div id='cu' style='text-align: center; font-size: 40pt'></div>\n");
setInterval(doCu, 1000);
doCu();
</script>
<body>
</body>
</html>
In order to pause and resume the counter you should save the return value of the setInterval funciton and clear it or create a new one for pause and resume. Here is the example:
let interval = setInterval(doCu, 1000)
doCu()
function stop() {
clearInterval(interval)
}
function resume() {
interval = setInterval(doCu, 1000)
}
Add that to the end of your script and add 2 buttons like the following in order to be able to test it.
<button onclick="stop()">
Pause
</button>
<button onclick="resume()">
Resume
</button>
To stop the timer after one hour you can add the following code
// Stop the timer after one hour has passed.
// setTimeout calls function stop (that is used to pause the timer aswell) after 1 hour
// 1000 milis is a second. Times 60 is a minute. Times 60 is an hour
setTimeout(stop, 1000 * 60 * 60)
For the timer to automatically stop after an hour from the moment you click resume change the resume function like this:
function resume() {
interval = setInterval(doCu, 1000)
// When you resume the timer, add a timeout so it will stop in an hour.
setTimeout(stop, 1000 * 60 * 60)
}
I have updated the fiddle so you can see how it is completed.
Updated JSFiddle Link
EDIT:
Made timer stop after an hour
Renamed pause function to stop so it is more clear what it does.
Added ability to stop timer after an hour after resume
Related
Im working on code for a simple stopwatch. Last obstacle for me is reset the time to zero. The function resetTimer is where i am trying to implement the code. So the webpage will display a page with a timer and three buttons; stop, start and reset. When a user clicks the reset button, the timer is supposed to reset back to zero. I have been having trouble trying to make it work. Any help/ideas would be clutch.
I hope i made myself clear. Again i am trying to make the timer reset to 00:00:00
window.onload = function () {
//grab possible elements needed
const timerEl = document.getElementById("timer-text")
const startBtn = document.getElementById("start")
const restartBtn = document.getElementById("restart");
const stopBtn = document.getElementById('stop');
//hold variables of time and set to 0
let hours = parseInt('0');
let minutes = parseInt('0');
let seconds = parseInt('0');
let time;
function makeTwoNumbers(num) {
if (num < 10) {
return "0" + num
}
return num
}
//timer
let timer = () => {
seconds++
//console.log(seconds)
if (seconds == 60) {
minutes++
seconds = 0;
hours = 0
}
if (minutes == 60) {
hours++
minutes = 0;
hours = 0;
}
timerEl.textContent = makeTwoNumbers(hours)+ ": " + makeTwoNumbers(minutes) + ": " + makeTwoNumbers(seconds);
}
let runTheClock;
//timer is running
function runTimer() {
runTheClock = setInterval(timer, 20);;
}
function stopTimer() {
clearInterval(runTheClock)
}
//function will reset timer
function resetTimer() {
time--;
timerEl.textContent;
if (time === 0) {
stopTimer();
time = 0
}
}
restartBtn.addEventListener("click", function () {
resetTimer();
})
//button will pause the timer
stopBtn.addEventListener("click", function () {
stopTimer();
})
//button will start the timer
startBtn.addEventListener("click", function () {
runTimer();
})
}
Here's a fixed and slightly refactored version.
<html>
<body>
<div id="timer-text"></div>
<button id="start">start</button>
<button id="restart">restart</button>
<button id="stop">stop</button>
</body>
<script>
const timerEl = document.getElementById("timer-text")
const startBtn = document.getElementById("start")
const restartBtn = document.getElementById("restart");
const stopBtn = document.getElementById('stop');
let runTheClock;
let seconds = 0;
render(seconds);
function makeTwoNumbers(num) {
return ((num < 10) ? "0" : "") + num;
}
function tick() {
seconds++;
render(seconds);
}
function render(secs) {
const hours = Math.floor(secs / 3600);
const minutes = Math.floor(secs / 60) - (hours * 60);
const seconds = secs % 60;
const val = [hours, minutes, seconds].map(makeTwoNumbers).join(":");
console.log(val);
timerEl.textContent = val;
}
function runTimer() {
runTheClock = setInterval(tick, 1000);
}
function stopTimer() {
clearInterval(runTheClock)
}
function resetTimer() {
seconds = 0;
render(seconds);
}
restartBtn.addEventListener("click", resetTimer);
stopBtn.addEventListener("click", stopTimer);
startBtn.addEventListener("click", runTimer);
</script>
</html>
In the reset function it just sets seconds back to 0 and sets the textContent value so it appears on the page. I separated out the calculating and drawing of the time into a render fucntion, so it can be reused whenever it needs to be re-rendered.
To explain the render function.
We only need to store the number of seconds as a persistent variable between the periodic function calls. We can derive hours and minutes from it. This makes it much less error prone than trying to increment hours and minutes as well.
To calculate hours we just divide seconds by 3600 (or 60 x 60 the number of seconds in an hour) and round down.
To calculate minutes we can calculate the number of total minutes (seconds / 60 and round down) then subtract the number of minutes in the hours value we calculated (hours * 60).
For seconds we use modulus or % which is just a fancy word for remainder. So seconds % 60 gives us the remainder value of seconds / 60. For example 61 % 60 = 1. This isn't the only way these values could be calculated.
To build the display string. I just put all of the hours, minutes and seconds in an array. Then used the map method, which applies the function makeTwoNumbers to all of the values. I then used the join method to join all the strings using the delimiter :. It just saves some typing and means you only reference makeTwoNumbers once, making it less work to use a different function later if you want to.
Hope that helps.
I realized that you could simply reset seconds, hours, and minutes to 0 and use a variable true. This would reset it entirely to 0. I couldnt believe how simple it was
I'm kinda new to programming, but recently I was trying to do little first project of mine called timer count, it's just simple local website which I open when I'm deciding to start programming during the day and it counts the time. I created 2 buttons with 2 different functions (start,stop), but the problem I'm stuck on is I don't know how to implement stop function. The idea is that timer should stop after button click, and when I click start button it should start from saved time.
Here's HTML/CSS code:
<div class="timer-display-id">
<h1>Timer </h1>
<p id="timer">00:00:00 </p>
<button id="start-timer" onclick="start()">Start </button>
<button id="stop-timer" onclick="stop()">Stop </button>
</div>
<script src="timer.js"></script>
and here's JS code:
function stop() {
// not exactly sure if this function should be here, anyway no idea what to add to get this to work
clearInterval(interval);
start.disabled = false;
}
function convertSec(cnt) {
let sec = cnt % 60;
let min = Math.floor(cnt / 60);
if (sec < 10) {
if (min < 10) {return "0" + min + ":0" + sec;}
else {return min + ":0" + sec;}
}
else if ((min < 10) && (sec >= 10)) {return "0" + min + ":" + sec;}
else {return min + ":" + sec;}
}
function start() {
let ret = document.getElementById("timer");
let counter = 0;
let start = document.querySelector("#start-timer");
let stop = document.querySelector("#stop-timer");
start.disabled = true;
let interval = setInterval(function() {
ret.innerHTML = convertSec(counter++); // timer start counting here...
},1000);
}
I understand it might be very messy, kinda lack of logic, but it's best I can do for now. If you'd like to give some tips about code organizing, I'd appreciate it.
You nee to have interval accessible by both functions whileit holds the setInterval function, just move it outside the start function :
const ret = document.getElementById("timer");
const startBtn = document.querySelector("#start-timer");
let counter = 0;
let interval;
function stop() {
clearInterval(interval);
startBtn.disabled = false;
}
function convertSec(cnt) {
let sec = cnt % 60;
let min = Math.floor(cnt / 60);
if (sec < 10) {
if (min < 10) {
return "0" + min + ":0" + sec;
} else {
return min + ":0" + sec;
}
} else if ((min < 10) && (sec >= 10)) {
return "0" + min + ":" + sec;
} else {
return min + ":" + sec;
}
}
function start() {
startBtn.disabled = true;
interval = setInterval(function() {
ret.innerHTML = convertSec(counter++); // timer start counting here...
}, 1000);
}
<div class="timer-display-id">
<h1>Timer </h1>
<p id="timer">00:00:00 </p>
<button id="start-timer" onclick="start()">Start </button>
<button id="stop-timer" onclick="stop()">Stop </button>
</div>
If you want the count to be saved after you hit "stop", and to re-start from the same point, you will need to define your count variable somewhere outside the start() function, so that it can tell what count to restart from. At the moment, count is local to the start() function, which will reset it to zero every time.
By using the 1s interval timer to update the count, your counter will round each period to whole seconds. It would be slightly more complicated, but if you want to be able to add up the partial seconds from multiple counts, it would be more accurate to use something like Date.getTime() to record the time the start button is pressed, then check the elapsed time when stop() is triggered, and add that to your count. You might still want to use an interval timer to regularly update the current value though. Again, you would need to check that the variables you want to use have the correct scope, so that they are visible to the functions that use them, and not lost between function calls.
I'm having a problem get this countdown timer to stop at zero so the time won't show as a negative value. The console.log is getting called and works fine but for some reason the clearInterval() is not. This is driving me crazy and I'm close to quitting.
const timerContainer = document.getElementById('timerContainer');
const THREEMINUTES = 60 * 0.1;//5 seconds for testing
startTimer(THREEMINUTES, timerContainer);
function startTimer(duration, display) {
let start = Date.now();
let diff, min, sec;
let timer = () => {
diff = duration - (((Date.now() - start) / 1000) | 0);
//use bitwise to truncate the float
min = (diff / 60) | 0;
sec = (diff % 60) | 0;
min = min < 10 ? '0' + min : min;
sec = sec < 10 ? '0' + sec : sec;
display.textContent = min + ':' + sec;
if (diff <= 0) {
stopTimer();
submit.disabled = 'true';
};
};
//call timer immediately otherwise we wait a full second
timer();
setInterval(timer, 1000);
function stopTimer() {
clearInterval(timer);
console.log("time's up", diff);
};
}
<div id="timerContainer"></div>
You are not saving the result of setInterval(timer, 1000);
you should use this:
let timerId;
timer();
timerId = setInterval(timer, 1000);
function stopTimer() {
clearInterval(timerId);
console.log("time's up", diff)
};
As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.
Don't pass the function that you want stopped to clearInterval().
Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.
// Function that the timer will invoke
function callback(){
. . .
}
// Set up and initiate a timer and capture a reference to its unique ID
var timerID = setInterval(callback, 1000);
// When needed, cancel the timer by passing the reference to it
clearInterval(timerID);
The code is fixed make sure you fix your submit button code.
You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.
const timerContainer = document.getElementById('timerContainer');
const THREEMINUTES = 60 * 0.1;//5 seconds for testing
startTimer(THREEMINUTES, timerContainer);
var timer = null;
function startTimer(duration, display) {
let start = Date.now();
let diff, min, sec;
let timer = () => {
diff = duration - (((Date.now() - start) / 1000) | 0);
//use bitwise to truncate the float
min = (diff / 60) | 0;
sec = (diff % 60) | 0;
min = min < 10 ? '0' + min : min;
sec = sec < 10 ? '0' + sec : sec;
display.textContent = min + ':' + sec;
if (diff <= 0) {
stopTimer();
submit.disabled = 'true';
};
};
//call timer immediately otherwise we wait a full second
timer();
timer = setInterval(timer, 1000);
function stopTimer() {
clearInterval(timer);
console.log("time's up", diff);
};
}
The user hits start after specifying a break period and time period in minutes (whole numbers) and calling timer.
The stopWatch called by timer works (albeit stopping at .01 seconds, to be figured out later).
I'd like the user to be able to specify a break period, after which the stopwatch resumes again and again (i.e., 30 min countdown, 5 min break, 30 min countdown, etc. until manual reset or stop). I thought using setInterval inside of the timer function to keep calling stopWatch forever -- if a breakTime existed -- would work, but I appear to be missing something. Unfortunately, it counts down and stops dead. Where am I going wrong?
function timer(minutes) {
let breakTime = parseInt($("#breakLength").html());
if (breakTime === 0) {
stopWatch(minutes);
} else {
setInterval(stopWatch(minutes), breakTime*60000);
}
}
function stopWatch (minutes) {
let initialize = new Date();
let deadLine = new Date(initialize.getTime() + minutes*60000);
intervalHandle = setInterval(function() {
let timeSet = Date.parse(deadLine) - Date.parse(new Date());
if (timeSet > 0) {
let total_seconds = (timeSet) / 1000;
let hours = Math.floor(total_seconds / 3600);
total_seconds = total_seconds % 3600;
let minutes = Math.floor(total_seconds / 60);
total_seconds = total_seconds % 60;
let seconds = Math.floor(total_seconds);
// display time as HH:MM:SS
hours = pretty_time_string(hours);
minutes = pretty_time_string(minutes);
seconds = pretty_time_string(seconds);
let currentTimeString = hours + ":" + minutes + ":" + seconds;
timeRemaining = timeSet;
console.log(currentTimeString);
$("#displayHours").html(hours);
$("#displayMins").html(minutes);
$("#displaySecs").html(seconds);
} else {
stopTimer(intervalHandle);
}
}, 1000);
}
Ryan, i think you never get the timer execution again just because your forget to launch it after timer completes.
I've refactor your version a little bit, so you can get the way you should change your code.
Hope this behaviour is what you want by default.
let tickHandler;
let breakHandler;
function kill() {
clearInterval(tickHandler);
clearTimeout(breakHandler);
}
function timer(minutes) {
let breakTime = parseFloat(document.querySelector('#breakTime').value, 10) * 60000;
startWatch(minutes, breakTime);
}
function display(deadLine) {
let displayDate = new Date(deadLine);
let hrs = displayDate.getUTCHours().toString();
let min = displayDate.getUTCMinutes().toString();
let sec = displayDate.getUTCSeconds().toString();
document.querySelector("#watch").value = hrs.padStart(2, '0') + ' : ' + min.padStart(2, '0') + " : " + sec.padStart(2, '0');
}
function startWatch(minutes, breakTime) {
breakHandler = setTimeout(function() {
let initialize = new Date(0);
let deadLine = new Date(minutes * 60000);
let currDate = Date.now();
display(deadLine);
tickHandler = setInterval(function() {
let timePass = Date.now() - currDate;
deadLine = deadLine - timePass;
if (deadLine > 0) {
let displayDate = new Date(deadLine);
display(displayDate);
currDate = Date.now();
} else {
clearInterval(tickHandler);
startWatch(minutes, breakTime);
}
}, 1000);
}, breakTime);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>BreakTime</label>
<input id="breakTime" value="0" />
<br/>
<button onclick="timer(1)">Start Timer</button>
<button onclick="kill()">Stop Timer</button>
<br/>
<br/>
<label>Left:</label><input id="watch" readonly="true" />
</body>
</html>
I have a stop watch which works good but in sec value after 60 sec i need the timer to go to zero and min to 1, And in the same way for every 60 sec min should change
/* Stopwatch */
starttime(){
console.log("timer started");
if( this.running == 0){
this.running = 1;
this.adder()
}else{
this.running = 0;
}
}
reset(){
console.log("timer reset");
this.running = 0;
this.time = 0;
this.total = 0;
this.Sec = 0;
}
adder(){
console.log("timer incrementor");
if(this.running == 1){
setTimeout(()=>{
this.time++;
var mins = Math.floor(this.time/10/60);
var sec = Math.floor(this.time / 10 );
var tens = this.time/10;
this.total = mins + ':' + sec;
console.log(this.total) ;
this.Sec = sec;
this.adder()
},10)
}
}
But here time changes, sec gets added up it does not goes to zero when it reaches 60 it moves on to 61,62,63.... sample time after 120 secs is 0:2:120, What i need is 0:2:0 (hrs:sec:min)
worked fine after modifying ' var sec = Math.floor(this.time / 10)%60;' and changed set time out time to
this.adder()
},100)
In case you have the option, use moment.js to format the elapsed time.
this.total = moment.utc(this.time).format("mm:ss.SSS"))
Otherwise ignore this answer ;)
I think your calculation for second is wrong. use following statement instead of yours.
var sec = Math.floor(this.time / 10)%60;