Countdown counter in Hours - javascript

I want to write code for a counter which countdown from 4 hours in hour, minute and second components (3:59:59 ... 3:59:58 ..... 0:0:1 ... 0:0:0) in which the user can increment or decrement any of those components by using +/-icons. I wrote a code but I cannot make it? How can I complete it? In my code just increase/decrease icon works.
function increment() {
hour = parseInt(document.getElementsByName("hour")[0].value);
minute = parseInt(document.getElementsByName("minute")[0].value);
second = parseInt(document.getElementsByName("second")[0].value);
if (second + 1 == 61) {
minute = minute + 1;
if (minute == 61) {
hour = hour + 1;
if (hour == 3) {
hour = 0;
}
minute = 0;
}
second = 0;
} else {
second += 1;
}
document.getElementsByName("hour")[0].value = hour.toString();
document.getElementsByName("minute")[0].value = minute.toString();
document.getElementsByName("second")[0].value = second.toString();
}
function decrement() {
hour = parseInt(document.getElementsByName("hour")[0].value);
minute = parseInt(document.getElementsByName("minute")[0].value);
second = parseInt(document.getElementsByName("second")[0].value);
if (second - 1 <= 0) {
minute -= 1;
if (minute <= 0) {
hour -= 1;
if (hour <= 0) {
hour = 2;
minute = 60;
} else {
minute = 60;
}
}
second = 60;
} else {
second -= 1;
}
document.getElementsByName("hour")[0].value = hour.toString();
document.getElementsByName("minute")[0].value = minute.toString();
document.getElementsByName("second")[0].value = second.toString();
}
<html>
<body>
<table>
<tr>
<td>Hour</td>
<td>
<input type="text" name = "hour" placeholder = "HOUR" value="0"/>
</td>
<td>Minute</td>
<td>
<input type="text" name="minute" placeholder="MINUTE" value="0"/>
</td>
<td>Second</td>
<td>
<input type="text" name="second" placeholder="SECOND" value="0"/>
</td>
</tr>
<tr>
<td><br>
<input type="button" name="+" value="+" onclick= "return increment()"/>
</td>
<td><br>
<input type="button" name="-" value="-" onclick="return decrement()"/>
</td>
</tr>
</table>
</body>
</html>

Here is how i would go about it, first of all, you had the script execute before the body which caused problems since the elements you were trying to select didn't exist yet,
also, you're trying to do everything everywhere, but if you keep state, it is much more manageable
<script>
const maxTime = 4 * 60 * 60; // 4 hours in seconds
const hours = document.querySelector("[name='hour']");
const minutes = document.querySelector("[name='minute']");
const seconds = document.querySelector("[name='second']");
let remaining = maxTime;
let counter = setInterval(decrement, 1000);
function increment() {
remaining = Math.max(maxTime, remaining + 1);
display();
}
function decrement() {
remaining = Math.max(0, remaining - 1);
display();
}
function display() {
const time = new Date(remaining * 1000).toISOString();
hours.value = time.slice(11, 13);
minutes.value = time.slice(14, 16);
seconds.value = time.slice(17, 19);
}
</script>

You can use the setInterval function
This will call your decrement function every second
setInterval(decrement, 1000)
The first parameter is the function to be executed.
The second parameter indicates the number of milliseconds before execution.

Related

how to display " backward timer " using JavaScript?

I have my DOM like this :
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
And my JavaScript Like this :
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - currentTime
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
now I want to display value in my web page But it doesn't updating. seems like its freezes. but my "setInterval()" running properly.
How can I resolve this issue? need help!
You need instead of this code
let output = value - currentTime
use this
let output = value - (currentTime * 1000)
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - (currentTime * 1000)
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
Based on #Oleg Barabanov's answer I found one bug. If you didn't enter any value in text box or first added value then click on "Reset" and click on "Go" button then counter started with negative value. I fixed that issue with this code.
Script
var intervalClear;
var input = document.querySelector('#input');
var mint = document.querySelector('#mint');
var sec = document.querySelector('#sec');
var go_button = document.querySelector('#button');
var reset_button = document.querySelector('#reset');
go_button?.addEventListener('click', () => {
if (input.value != '' && input.value != 0 && parseInt(input.value) != NaN) {
startTimer(input.value, mint, sec);
}
});
reset_button?.addEventListener('click', () => {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
});
function startTimer(duration, minElement, secElement) {
clearInterval(intervalClear);
var timer = duration * 60, minutes, seconds;
intervalClear = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
minElement.textContent = minutes;
secElement.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (minutes == 0 && seconds == 0) {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
}
}, 1000);
}
DOM
<input type="number" id="input" placeholder="Enter time in minutes" >
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint">00</div>
<div class="sec" id="sec">00</div>
</div>

how to submit timer value in a form when click stop?

how can i make this timer to submit form name as in name="time" and send value to $_POST['time'] when someone clicks stop and then the value i can store it into mysql database?
<div id="timer"></div>
<button type="button" onclick="stopTimer()">Stop</button>
<?php
$time = strtotime('01:00:00');
?>
<script>
var startTime = <?php echo $time;?>;
//var startTime = Date.now();
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var container = document.getElementById('timer');
function stopTimer() {
clearInterval(timer);
}
function pad(n){
return ('00' + n).slice(-2);
}
var timer = setInterval(function(){
var currentTime = Date.now();
var difference = currentTime - startTime;
var hours = pad((difference / hour) | 0);
var minutes = pad(((difference % hour) / minute) | 0);
var seconds = pad(((difference % minute) / second) | 0);
container.innerHTML = hours + ':' + minutes + ':' + seconds;
// This only represents time between renders. Actual time rendered is based
// on the elapsed time calculated above.
}, 250);
</script>
thanks for your help
As #brombeer suggested, just create a form like this:
<form action="yoururl" method="post">
<input id="timer" type="number" disabled name="time" value="<?=$time?>" /> <!--here the value is shown-->
<button type="submit">Stop</button> <!--when you click here time=xx:xx:xx is sent to yoururl-->
</form>
You can then access it from JavaScript as timer and edit it ad shown in your question

Errors while calculating time difference

actual output and expected outputs are mentioned in snapshots :[Snapshot of case 1][1][Snap Shot of Case2 ][2].
I get errors while calculating time difference between start-time and end-time. The errors:
If start-time is greater than end-time then calculation is wrong.
If weekends is included and start-time is greater than end-time.
Please suggest how to resolve the errors in my code.
// Wire up Date and DateTime pickers (with default values)
$("#start").datetimepicker();
$("#end").datetimepicker();
$("#workday_start").timepicker({
hour: 8
}).val("8:00");
$("#workday_end").timepicker({
hour: 17
}).val("17:00");
// Calculate the number of hours worked
$("#calculate").click(function() {
// Are all fields complete?
var allFieldsComplete = $('.data input').filter(function() {
return $(this).val().toString().length == 0;
}).length == 0;
// Ensure all fields are present
if (allFieldsComplete) {
// Capturing the input dates
var startDate = moment($("#start").val());
var endDate = moment($("#end").val());
var daysDiff = endDate.diff(startDate, 'days');
// Capturing the input times
var startTime = startDate.hours();
var endTime = endDate.hours();
var timeDiff;
var operational_hr_start = new Date("1/1/0001 " + $("#workday_start").val()).getHours() + (new Date("1/1/0001 " + $("#workday_start").val()).getMinutes() / 60)
var operational_hr_end = new Date("1/1/0001 " + $("#workday_end").val()).getHours() + (new Date("1/1/0001 " + $("#workday_end").val()).getMinutes() / 60);
var includeWeekends = $('input[type=checkbox]').prop('checked');
if (startTime < operational_hr_start) {
startTime = operational_hr_start;
}
if (endTime > operational_hr_end) {
endTime = operational_hr_end;
}
timeDiff = endTime - startTime;
if (daysDiff > 0) {
var response= workingHoursBetweenDates(startDate, endDate, operational_hr_start, operational_hr_end, includeWeekends);
$("#result").val(response);
} else if (daysDiff === 0) {
var dayNo = startDate.day();
if (dayNo === 0 || dayNo === 6) {
alert('Weekend!!!');
return;
} else {
if (timeDiff > 0) {
alert('Total hours worked: ' + timeDiff);
} else {
alert('End time must be greater than start time!!!');
}
}
} else {
alert('End date must be greater than start date!!!');
}
} else {
// One or more of the fields is undefined or empty
alert("Please ensure all fields are completed.");
}
});
});
// Simple function that accepts two parameters and calculates the number of hours worked within that range
function workingHoursBetweenDates(startDate, endDate, operationalHourStart, operationalHourEnd, includeWeekends) {
var incrementedDate = startDate;
var daysDiff = endDate.diff(startDate, 'days');
var workingHrsPerDay = operationalHourEnd - operationalHourStart;
var startHrs = startDate.hours(),
endHrs = endDate.hours(),
totalHoursWorked = 0;
if (startDate.hours() < operationalHourStart) {
startHrs = operationalHourStart;
}
if (endDate.hours() > operationalHourEnd) {
endHrs = operationalHourEnd;
}
/*
* The below block is to calculate the duration for the first day
*
*/
{
totalHoursWorked = operationalHourEnd - startHrs;
if (startDate.day() === 0 || startDate.day() === 6) {
totalHoursWorked = 0;
if (includeWeekends) {
totalHoursWorked = operationalHourEnd - startHrs;
}
}
incrementedDate = incrementedDate.add(1, 'day');
}
/*
* The below if block is to calculate the duration for the last day
*
*/
{
var lastDayWorkHrs = endHrs - operationalHourStart;
totalHoursWorked = totalHoursWorked + lastDayWorkHrs;
if (endDate.day() === 0 || endDate.day() === 6) {
if (includeWeekends) {
totalHoursWorked = totalHoursWorked + lastDayWorkHrs;
} else {
totalHoursWorked = totalHoursWorked - lastDayWorkHrs;
}
}
}
// The below for block calculates the total no. of hours excluding weekends. Excluding first and last day
for (var i = 1; i < daysDiff; i++) {
/*
* Weekname mapping. There are default week
* numbers (i.e., 0 to 6. 0 means Sunday, 1 means Monday, ... 6 means Saturday)
* which are returned by moment library.
*
*/
if (incrementedDate.day() === 0 || incrementedDate.day() === 6) {
// Do nothing
if (includeWeekends) {
totalHoursWorked = totalHoursWorked + workingHrsPerDay;
}
} else {
totalHoursWorked = totalHoursWorked + workingHrsPerDay;
}
incrementedDate = incrementedDate.add(1, 'day');
}
return totalHoursWorked;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<pre>Variables</pre>
<table>
<tr>
<th>START</th>
<th>END</th>
<th>WORKDAY START</th>
<th>WORKDAY END</th>
<th>Result</th>
<th>INCLUDE WEEKENDS?</th>
</tr>
<tr class='data'>
<th><input id='start' /></th>
<th><input id='end' /></th>
<th><input id='workday_start' /></th>
<th><input id='workday_end' /></th>
<th><input id='result' value=" "/></th>
<th><input id='include_weekends' type='checkbox' /></th>
</tr>
</table>
<hr />
<input id='calculate' type='button' value='Calculate Hours Worked' />

Resetting a timer

I have a countdown timer for clicking a button at 0 second and it works but I want the time itself to reset after the click. Using this code I want Time 1 to be reset when work2 is clicked
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(:\d\d:\d\d)/)[0];
}
function startTimer() {
var nextElem = $(this).parents('td').next();
var duration = nextElem.text();
var a = duration.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
setInterval(function() {
seconds--;
if (seconds >= 0) {
nextElem.html(toTimeString(seconds));
}
if (seconds === 0) {
document.getElementById('work2').click();
clearInterval(seconds);
}
}, 1000);
}
$('.lazy').on('click', startTimer);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input id="work1" class="lazy" type="button" value="Time 1"/>
</td>
<td>:00:05</td>
</tr>
<tr>
<td>
<input id="work2" class="lazy" type="button" value="Time 2" type="button" />
</td>
<td>:10:00</td>
</tr>
</table>
Timers are used like this: You start the timer and store the timer handle in a variable. When stopping the timer, you hand over this variable.
var timer1 = setInterval(function(){}, 1000);
..
clearInterval(timer1);

How to put Stop and Reset button in html and javascript

I need help,
How to put Stop and Reset button in html and javascript
Here my countdown javascript and html code and also put chrome notifications with sound,
sounds loop notify me left 10 Seconds after countdown then 0 notify me in chrome notification, and also show countdown value in page title
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
var t=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
var t=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
And also html
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<!--<input type="button" value="Reset" id="reset">-->
</form>
<div id="countdown_div"> </div>
javascript
changes
1.taken window variables t1,t2 where the timers are going to be assigned
2.added a button(name:reset),which on click calls doReset function
3.added doStuff function
window.t1=null;
window.t2=null;
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
window.t1=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
window.t2=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
function doReset(){
window.clearTimeout(window.t1);
window.clearTimeout(window.t2);
document.getElementById('countdown_div').innerHTML="";
}
HTML
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<input type="button" onClick="return doReset();" value="Reset" id="reset">
</form>
<div id="countdown_div"> </div>
Use the reset attribute in your form to clear the form input values
<input type="reset"value="Reset">
Take a look here http://jsfiddle.net/05y89wn3/14/
you have to clear the timeout ,reset the form and change the html value of the countdown_div
var reset = document.getElementById("reset_button");
var t;
reset.onclick = function() {
clearTimeout(t);
document.getElementById("countdown_form").reset();
document.getElementById("countdown_div").innerHTML="";
}

Categories