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);
Related
I am building a cart booking system. Since bookings can be from 1 hour to 6 hours, there must be a countdown timer using the time stored in the database. All booked carts are displayed in a table, with a countdown timer for each cart stored in the database.
<table id="example" class="table table-striped dt-responsive nowrap" width="100%"
cellspacing="0">
<thead class="thead-light">
<tr>
<th>
#Html.DisplayNameFor(model => model.CartNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.CartType)
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th>
#Html.DisplayNameFor(model => model.CustomerID)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration)
</th>
<th>
Remaining Time
</th>
<th>
#Html.DisplayNameFor(model =>
model.ImageContent)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem =>
item.CartNumber)
</td>
<td>
#Html.DisplayFor(modelItem =>
item.CartType)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.DisplayFor(modelItem =>
item.CustomerID)
</td>
<td>
#Html.DisplayFor(modelItem =>
item.Duration)
</td>
<td>
<p class="demo#(item.ID)"></p>
</td>
<td>
<img height="50" width="70"
src='#Url.Action( "BookedCarts", "File", new { id = item.ID })' />
</td>
</tr>
}
</tbody>
</table>
<script>
// Set the date we're counting down to
var countDownDate = new Date('#item.DurationCountdown').getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 *
60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
//document.getElementsByClassName('demo')[0].innerHTML = hours + "h "
// + minutes + "m " + seconds + "s ";
[... document.getElementsByClassName("demo#(item.ID)")].forEach(e =>
e.innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementsByClassName("demo")[0].innerHTML = "EXPIRED";
}
}, 1000);
</script>
My challenge is that only one timer is displayed for all carts; I want all the booked carts to display unique countdown timers based on the hours booked. Below is my code. I am using JavaScript Countdown Timer and ASP.NET Core MVC with Razor Pages, and I will greatly appreciate any help.
In my opinion, I think we don't need to think about how to save the remain time in our database. The records are useless when the orders were finished, they should be deleted to save the resource.
Countdown based on creating records, I think this fits the countdown you want to be unique.
As you know, when you created a new record and it will have the createTime. And I don't know what the bookings time value, so I assume it is 2 hours, you can accord to your business to change it. Then I can accord to the createTime to get the remain seconds like below.
Then we don't need to store the remain time in our database, every time when we refresh the page, it will returns the exact time with the entity data.
I also find a good countdown sample for you. You can check the source code and use it in your page. We just need to replace the value of data.
Source Code:
/**
* Plugin
* #author Tungse
* #param dayTag show day html
* #param hourTag show hour html
* #param minTag show minutes html
* #param secTag show second html
* #param dayClass bind day tag ClassName
* #param hourClass bind hours tag ClassName
* #param minClass bind minutes tag ClassName
* #param secClass bind seconds tag ClassName
* #param isDefault whether use default tagTemp
* #param showTemp show template 0:(day hour min sec) 1:(hour min sec)
* #param backfun finish callback
*/
(function ($) {
$.fn.countdownsync = function (tagTemp, backfun) {
var data = "";
var _DOM = null;
var _defaultTag = _TempTag = {
dayTag: "<li class='countdownday'></li><li class='split'>day</li>",
hourTag: "<li class='countdownhour'></li><li class='split'>:</li>",
minTag: "<li class='countdownmin'></li><li class='split'>:</li>",
secTag: "<li class='countdownsec'></li><li class='split'>:</li>",
dayClass: ".countdownday",
hourClass: ".countdownhour",
minClass: ".countdownmin",
secClass: ".countdownsec",
isDefault: false,
showTemp:0
};
var _temp = $.extend(_TempTag, tagTemp);
var TIMER;
createdom = function (dom) {
_DOM = dom;
data = Math.round($(dom).attr("data"));
var htmlstr = (_temp.showTemp == 0 ? _temp.dayTag : "") + _temp.hourTag + _temp.minTag + _temp.secTag;
if (_temp.isDefault) {
htmlstr = (_temp.showTemp == 0 ? _defaultTag.dayTag : "") + _defaultTag.hourTag + _defaultTag.minTag + _defaultTag.secTag;
htmlstr = "<ul class='countdown'>" + htmlstr + "</ul>";
$("head").append("<style type='text/css'>.countdown {list-style:none;}.countdown li{float:left;background:#000;color:#fff;border-radius:50%;padding:10px;font-size:14px; font-weight:bold;margin:10px;}.countdown li.split{background:none;margin:10px 0;padding:10px 0;color:#000000;}</style>");
}
$(_DOM).html(htmlstr);
reflash();
};
reflash = function () {
var range = data,
secday = 86400, sechour = 3600,
days = parseInt(range / secday),
hours = _temp.showTemp == 0 ? parseInt((range % secday) / sechour) : parseInt(range / sechour),
min = parseInt(((range % secday) % sechour) / 60),
sec = ((range % secday) % sechour) % 60;
data--;
if (range < 0) {
window.clearInterval(TIMER); //clear timer
} else {
$(_DOM).find(_temp.dayClass).html(nol(days));
$(_DOM).find(_temp.hourClass).html(nol(hours));
$(_DOM).find(_temp.minClass).html(nol(min));
$(_DOM).find(_temp.secClass).html(nol(sec));
}
if ((range - 1) == 0) {
undefined == backfun ? function () { } : backfun();
}
};
TIMER = setInterval(reflash, 1000);
nol = function (h) {
return h > 9 ? h : '0' + h;
};
return this.each(function () {
var $box = $(this);
createdom($box);
});
};
})(jQuery);
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>countdown plugin</title>
<style>
h3{margin-top: 30px}
.ys1{
color: #009AC1;
font-weight: bold;
}
.ys2{
color: #2FAB11;
font-weight: bold;
}
.ys3{
color: #C16000;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h3>60s countdown</h3>
<p>data="60" </p>
<div class="container timeBar ys1" data="60" ></div>
<h3>600s countdown</h3>
<p>data="600" </p>
<div class="container timeBar ys2" data="600" ></div>
<h3>160000s countdown</h3>
<p>data="160000" </p>
<div class="container timeBar ys3" data="160000" ></div>
</div>
<script src="https://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="countdown.js"></script>
<script type="text/javascript">
$(function(){
$(".timeBar").each(function () {
$(this).countdownsync({
dayTag: "",
hourTag: "<label class='tt hh dib vam'>00</label><span> hours </span>",
minTag: "<label class='tt mm dib vam'>00</label><span> minutes </span>",
secTag: "<label class='tt ss dib vam'>00</label><span> seconds </span>",
dayClass: ".dd",
hourClass: ".hh",
minClass: ".mm",
secClass: ".ss",
isDefault: false,
showTemp:1
}, function () {
location.reload();
});
});
});
</script>
</body>
</html>
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 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
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.
I want to get totalTime to be in readable format for every time user login but by this i only get time for id(1) ,for rest it shows in milliseconds.how can i do this.m using javascript +jsp+springmvc+hibernate
<%#page import=" com.ephesoft.timesheet.core.model.LoginLog"%>
<%#page import="java.util.List"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function convertTime(milliSeconds) {
var str, days, hours, minutes, seconds;
if (milliSeconds > 0) {
milliseconds = milliSeconds;
days = Math.floor(milliseconds / (24 * 60 * 60 * 1000));
if (days < 0) {
days = 0;
}
milliseconds -= days * 24 * 60 * 60 * 1000;
hours = Math.floor(milliseconds / (60 * 60 * 1000));
if (hours < 0) {
hours = 0;
}
milliseconds -= hours * 60 * 60 * 1000;
minutes = Math.floor(milliseconds / (60 * 1000));
if (minutes < 0) {
minutes = 0;
}
milliseconds -= minutes * 60 * 1000;
seconds = Math.floor(milliseconds / (1000));
if (seconds < 0) {
seconds = 0;
}
} else {
days = hours = minutes = seconds = 0;
}
str = days + ":" + hours + ":" + minutes + ":" + seconds;
return str;
};
</script>
</head>
<table border="1">
<thead>
<tr>
<td>Login Id</td>
<td>Login Time</td>
<td>Logout Time</td>
<td>Total Time(in Minutes)</td>
</tr>
</thead>
<--- changes for Date --->
<%
List<LoginLog> log = (List<LoginLog>) r equest.getAttribute("loginList");
if(log != null) {
for(LoginLog login : log) {
String format = new SimpleDateFormat("EEE, d MMM yyyy ", Locale.ENGLISH).format(login.getLoginTime());
%>
<--- --->
<tr>
<td><%=login.getId()%></td>
<td><%=login.getLoginTime()%></td>
<td><%=login.getLogoutTime()%></td>
<td id="a"><span id="time"><%=login.getTotalTime()%></span> <script>
var milliSeconds = document.getElementById("time").innerHTML;
var c = convertTime(milliSeconds);
document.getElementById("a").innerHTML = c;
</script></td>
</tr>
<%
}
}
%>
</table>
</form>
</body>
</html>
can anyone please tell me appropriate way? THANKS.
Your problem is with this piece of code
<table border="1">
<thead>
<tr>
<td>Login Id</td>
<td>Login Time</td>
<td>Logout Time</td>
<td>Total Time(in Minutes)</td>
</tr>
</thead>
<%
List<LoginLog> log = (List<LoginLog>)request.getAttribute("loginList");
if(log != null) {
for(LoginLog login : log) {
%>
<tr>
<td><%=login.getId()%></td>
<td><%=login.getLoginTime()%></td>
<td><%=login.getLogoutTime()%></td>
<!-- changes -->
<td id="a<%=login.getId()%>"><span id="time<%=login.getId()%>"><%=login.getTotalTime()%></span> <script>
var milliSeconds = document.getElementById("time<%=login.getId()%>").innerHTML;
var c = convertTime(milliSeconds);
document.getElementById("a<%=login.getId()%>").innerHTML = c;
</script></td>
</tr>
<%
}
}
%>
</table>
You are creating several rows, and for all of them have th same id "time" then when you say in JS to
getElementById("id")
Will find the first occurences, thats why you always have the same date.
To make it work you should make your id unique, here is an option:
<span id="time<%login.getId()%>">
And later in your JS code
var milliSeconds = document.getElementById("time"<%=login.getId()%>).innerHTML;