mysql value to timer and keep increasing and updating till click stop? - javascript

i am a situation here, i have a mysql table called attendance and there is a column named "break" in mysql TIME format 00:00:00 now i need a way to update the time according to user id upon when user clicks start and stop it when clicks stop.
found this bit of code here now can someone guide me through to achieve my goal?
my sql query is
$stmt = $db->prepare("SELECT MAX(attn_id) AS id FROM attendance WHERE member_id = '".$_SESSION['member_id']."'");
$stmt->execute();
$row = $stmt->fetch();
timervalue = $row['break'];
$stmt = $db->prepare("UPDATE attendance SET break = '".timervalue."' WHERE attn_id= '".$row['id']."'");
$stmt->execute();
by default the value in break is stored as 00:00:00
how can i impliment the below code to make it update my database? also get rid of the milliseconds i only need h:m:s
<script type='text/javascript'>
$(function() {
// Some global variables
var startTime = 0,
elapsed = 0,
timerId = 0,
$timer = $("#timer");
function formatTime(time) {
var hrs = Math.floor(time / 60 / 60 / 1000),
min = Math.floor((time - hrs*60*60*1000) / 60 / 1000),
sec = Math.floor((time - hrs*60*60*1000 - min*60*1000) / 1000);
hrs = hrs < 10 ? "0" + hrs : hrs;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
return hrs + ":" + min + ":" + sec;
}
function elapsedTimeFrom(time) {
return formatTime(time - startTime + elapsed);
}
function showElapsed() {
$timer.text(elapsedTimeFrom(Date.now()));
}
function startTimer() {
// React only if timer is stopped
startTime = startTime || Date.now();
timerId = timerId || setInterval(showElapsed, 1000);
}
function pauseTimer() {
// React only if timer is running
if (timerId) {
clearInterval(timerId);
elapsed += Date.now() - startTime;
startTime = 0;
timerId = 0;
}
}
function resetTimer() {
clearInterval(timerId);
$timer.text("01:00:00");
startTime = 0;
elapsed = 0;
timerId = 0;
}
function editTimer() {
pauseTimer();
$timer.prop("contenteditable", true);
$timer.css("border", "1px solid red");
}
function setElapsed() {
var time = $timer.text(),
arr = time.split(":");
$timer.prop("contenteditable", false);
$timer.css("border", "1px solid black");
elapsed = parseInt(arr[0]*60*60, 10);
elapsed += parseInt(arr[1]*60, 10);
elapsed += parseInt(arr[2], 10);
elapsed *= 1000;
}
function sendTime() {
pauseTimer();
// Set hidden input value before send
$("[name='time']").val(formatTime(elapsed));
}
$("[name='start']").click(startTimer);
$timer.dblclick(editTimer);
$timer.blur(setElapsed);
$("form").submit(sendTime);
});
</script>
<h1><div id="timer">00:00:00</span></div>
<form action="" method="post">
<input type="button" name="start" value="Start">
<input type="submit" name="action" value="Submit">
<input type="hidden" name="time" value="00:00:00">
</form>
Really appreciate whole hearty for helping me ot and giving your valuable time and input.
Thanks

Here's a 'proof-of-concept'...
<?php
/*
-- TABLE CREATION STATEMENTS
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
//If something was posted, update the table. Otherwise, skip this step...
if(sizeof($_POST) != 0){
$x=$_POST['tts'];
$query = "UPDATE my_table SET t = SEC_TO_TIME(?) LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute([$x]);
}
//Grab the stored value from the database...
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
//Format the data for ease of use...
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
//Make a simple form, with one, hidden input...
<form id="myForm" method="post">
<input name="tts" type= "hidden" id="tts" value="tts">
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit">Save</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- The timer/stopwatch thingy-->
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
<!-- Also provide data in seconds, for ease of use -->
<!-- Note, this is 'val', not 'text' -->
$("#tts").val(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>

Related

javascript function is not working on button click. But working without button click

In this function, I have implemented a timer which is working fine in the given html input box without onclick function 'start_test'. but i want to start this inner function on button click which is not working. PLease help me to find the mistake.
function start_test() {
var hms = "01:30:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
if( seconds > 0 ){
function secondPassed() {
var minutes = Math.round((seconds - 30)/60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = " " +minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
//form1 is your form name
document.form_quiz.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
}
<div class="col-md-4" style="text-align: right;">
<button class="btn btn-primary" id="start_test" onclick="start_test();" >Start Test</button>
<input type="hidden" value="<?php echo date('M d Y');?>" id="c_month">
<h2><time id="countdown">01:30:00</time> </h2>
</div>
in setInterval(timePassed, 1000) this is 1s or MORE
=> 1000mms is just an indication, the time elapsed depend of the proccessor usage
PROOF:
const one_Sec = 1000
, one_Min = one_Sec * 60
, one_Hour = one_Min * 60
, biDigits = t => t>9?t:`0${t}`
, c_pseudo = document.getElementById('countdownP')
, c_real = document.getElementById('countdownR')
, btTest = document.getElementById('bt-test')
;
btTest.onclick=()=>
{
btTest.disabled = true
let [t_h,t_m,t_s] = '01:30:00'.split(':').map(v=>+v)
, timeEnd = new Date().getTime() + (t_h * one_Hour) + (t_m * one_Min) + (t_s * one_Sec)
, timerRef = setInterval(timePassed, 1000) // 1s or MORE !
;
function timePassed()
{
if (--t_s <0) { t_s = 59; --t_m}
if (t_m <0) { t_m = 59; --t_h }
c_pseudo.textContent = `${biDigits(t_h)}:${biDigits(t_m)}:${biDigits(t_s)}`
let tim = timeEnd - (new Date().getTime())
let tr_h = Math.floor(tim / one_Hour)
let tr_m = Math.floor((tim % one_Hour) / one_Min )
let tr_s = Math.floor((tim % one_Min ) / one_Sec )
c_real.textContent = `${biDigits(tr_h)}:${biDigits(tr_m)}:${biDigits(tr_s)}`
if ( !t_h && !t_m && !t_s)
{
btTest.disabled = false
clearInterval(timerRef)
}
}
}
<button id="bt-test" >Start Test</button>
<h2> pseudo count down <span id="countdownP">01:30:00</span> </h2>
<h2> real count down <span id="countdownR">01:30:00</span> </h2>
This statement is declaring a function countdownTimer, not executing it.
var countdownTimer = setInterval('secondPassed()', 1000);
Try replacing with:
setInterval(() => secondPassed(), 1000);
This should actually execute setInterval

Why does enabling timer to auto start disable my stop and reset buttons?

Thanks for any help here, not sure what's going on - but when I enable the timer(); line in order to automatically start the timer when the page is loaded, it disables the stop and reset buttons. I tried to only include relevant code here. Can anyone shed some light on why this is happening? Thank you in advance!
const startstop = () => {};
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
//console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
//var SAMSINPUTtest = parseInt(document.getElementById("input"));
//setInterval(function doIncrement() {
// goal += 1;
//}, SAMSINPUT * 1000); // *1000 to convert from seconds to milliseconds
var output2 = document.getElementById('output2');
setInterval(function doIncrement() {
goal += 1;
output2.innerHTML = goal.toString();
}, SAMSINPUT * 1000)
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
t;
// Get time from cookie
var cookieTime = null; //getCookie('time'); // for test
// If timer value is saved in the cookie
if (cookieTime != null && cookieTime != '00:00:00') {
var savedCookie = cookieTime;
var initialSegments = savedCookie.split('|');
var savedTimer = initialSegments[0];
var timerSegments = savedTimer.split(':');
var seconds = parseInt(timerSegments[2]),
minutes = parseInt(timerSegments[1]),
hours = parseInt(timerSegments[0]);
timer();
document.getElementById('timerValue').textContent = savedTimer;
$('#stop').removeAttr('disabled');
$('#reset').removeAttr('disabled');
} else {
var seconds = 0,
minutes = 0,
hours = 0;
timerDiv.textContent = "00:00:00";
}
// New Date object for the expire time
var curdate = new Date();
var exp = new Date();
// Set the expire time
exp.setTime(exp + 2592000000);
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
timerDiv.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") +
":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" + (seconds > 9 ? seconds : "0" + seconds);
// Set a 'time' cookie with the current timer time and expire time object.
var timerTime = timerDiv.textContent.replace("%3A", ":");
//console.log('timerTime', timerTime);
//setCookie('time', timerTime + '|' + curdate, exp);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer(); // autostart timer
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
reset.onclick = function() {
timerDiv.textContent = "00:00:00";
seconds = 0;
minutes = 0;
hours = 0;
//setCookie('time', "00:00:00", exp);
}
/**
* Javascript Stopwatch: Button Functionality
*
*/
$('#start').on('click', function() {
$('#stop').removeAttr('disabled');
$('#reset').removeAttr('disabled');
});
$('#stop').on('click', function() {
$(this).prop('disabled', 'disabled');
});
$('#reset').on('click', function() {
$(this).prop('disabled', 'disabled');
});
/**
* Javascript Stopwatch: Cookie Functionality
*
*/
function setCookie(name, value, expires) {
document.cookie = name + "=" + 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;
}
body {
background-color: powderblue;
}
p {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="startstop();">
<p> SAMS VALUE:
<a id="output"></a>
</p>
<p> GOAL:
<a id="output2"></a>
</p>
<button style="background-color:green" type="button" onClick="onClick()">ACTUAL</button>
<p>Actual Count: <a id="clicks">0</a></p>
<div class="container">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"></time>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success">START</button>
<button id="stop" class="btn btn-danger" disabled="disabled">STOP</button>
<button id="reset" class="btn btn-default" disabled="disabled">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"></div>
</div>
</div>
</div>
</body>

Showing Multiple Timers PHP + Javascript

I'm working on having multiple timers run in Javascript with the user data and time remaining pulled from a PHP + MySQL instance
Currently I have the following PHP Code:
<?php
$now = strtotime("now");
$allArrested = $conn->query("SELECT `user_id` FROM `user_jail` WHERE `jail_stop` > '$now'") or die(mysqli_error($conn));
if($allArrested->num_rows > 0){
while($arrested = $allArrested->fetch_assoc()){
foreach($arrested as $jailTime){
$checkTime = $conn->query("SELECT `jail_stop` FROM `user_jail` WHERE `user_id` = '$jailTime'") or die(mysqli_error($conn));
while($letsTime = $checkTime->fetch_assoc()){
$x = $letsTime['jail_stop'];
$letGo = $x - $now;
foreach($arrested as $convict){
echo "<div>".usernameById($convict)." for <span class=\"time\">".$letGo."</span></div>";
}
}
}
}
}
?>
And the following javascript:
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = 0;
display.textContent = "";
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = <?php echo $letGo; ?>,
display = document.querySelector('.time');
startTimer(fiveMinutes, display);
};
</script>
For testing purposes I have 4 different usernames. Currently only the first one is counting down.
The other 3 users counters remain on 90sec (variable $letGo).
Is anyone able to help me with this?

Pausing Javascript Timer

How to pause this timer? And if it's paused how to unpause and continue counting? It should be a function
function timer($time) {
let $lorem = $("#lorem");
function countdown() {
let $minutes = Math.floor($time / 60);
let $seconds = $time % 60;
let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);
--$time;
$lorem.text($result);
}
countdown();
setInterval(countdown, 1000);
}
timer(200);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lorem"></div>
You can do this by storing the result of setInterval in a variable:
var timeKeeper = setInterval(countdown, 1000);
Then when you want to pause, use clearInterval:
clearInterval(timeKeeper);
This will stop the interval from executing. To start again, reset the timer variable:
timeKeeper= setInterval(countdown, 1000);
Use a flag pause with a click event, on click toogle pause:
let pause = false;
$lorem.on('click', function() {
pause = !pause;
});
Then check if !pause and time > 0 then reduce the time by 0.1s
If the time <= 0 to remove the interval just call clearInterval(setInt) (note you need to define it first like let setInt = setInterval(countdown, 100);)
Using 100ms because better precision when you pause, otherwise after a click, your clock still gonna run into next sec then stop.
If !pause then $time = $time - 0.1; continue. Otherwise keep the same time and pass to next call.
function timer($time) {
let $lorem = $("#lorem");
let pause = false;
let setInt = setInterval(countdown, 100);
$('#pause').on('click', function() {
pause = !pause;
});
function countdown() {
if (!pause && $time > 0) {
$time = ($time - 0.1).toFixed(1);
}
if($time <= 0){
clearInterval(setInt);
}
let $minutes = Math.floor($time / 60);
let $seconds = Math.ceil($time % 60);
let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);
$lorem.text($result);
console.log($time);
}
}
timer(3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lorem"></div>
<br>
<button id="pause">Pause</button>

plain count up timer in javascript

I am looking for a simple count up timer in javascript. All the scripts I find are 'all singing all dancing'. I just want a jQuery free, minimal fuss count up timer that displays in minutes and seconds. Thanks.
Check this:
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<label id="minutes">00</label>:<label id="seconds">00</label>
Timer for jQuery - smaller, working, tested.
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
$("#seconds").html(pad(++sec%60));
$("#minutes").html(pad(parseInt(sec/60,10)));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="minutes"></span>:<span id="seconds"></span>
Pure JavaScript:
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
}, 1000);
<span id="minutes"></span>:<span id="seconds"></span>
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
Fiddle
The following code works as a count-up timer. It's pure JavaScript code which shows hour:minute:second. It also has a STOP button:
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
++totalSeconds;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
if(hour < 10)
hour = "0"+hour;
if(minute < 10)
minute = "0"+minute;
if(seconds < 10)
seconds = "0"+seconds;
document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
}
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it's single digit
s = checkTime(s); // add a leading zero if it's single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.
Extending from #Chandu, with some UI added:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue;
border-radius: 4px;
height: 40px;
width: 100px;
color: white;
font-size: 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: 0;
}
#minutes, #seconds {
font-size: 40px;
}
.bigger {
font-size: 40px;
}
.button {
box-shadow: 0 9px #999;
}
.button:hover {background-color: hotpink}
.button:active {
background-color: hotpink;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>
function pad(val) {
valString = val + "";
if(valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function set_timer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
function stop_timer() {
clearInterval(my_int);
}
</script>
Looks as follows:
Fiddled around with the Bakudan's code and other code in stackoverflow to get everything in one.
Update #1 : Added more options. Now Start, pause, resume, reset and restart. Mix the functions to get desired results.
Update #2 : Edited out previously used JQuery codes for pure JS and added as code snippet.
For previous Jquery based fiddle version : https://jsfiddle.net/wizajay/rro5pna3/305/
var Clock = {
totalSeconds: 0,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
reset: function () {
Clock.totalSeconds = null;
clearInterval(this.interval);
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
delete this.interval;
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
},
restart: function () {
this.reset();
Clock.start();
}
};
document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });
document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });
document.getElementById("resumeButton").addEventListener("click", function () { Clock.resume(); });
document.getElementById("resetButton").addEventListener("click", function () { Clock.reset(); });
document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
<span id="min">00</span>:<span id="sec">00</span>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
<input id="resetButton" type="button" value="Reset">
<input id="restartButton" type="button" value="Restart">
#Cybernate, I was looking for the same script today thanks for your input. However I changed it just a bit for jQuery...
function clock(){
$('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
$('#clock > #seconds').html(pad(totalSeconds%60));
$('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
}
$(document).ready(function(){
clock();
});
the css part:
<style>
#clock {
padding: 10px;
position:absolute;
top: 0px;
right: 0px;
color: black;
}
</style>
Note: Always include jQuery before writing jQuery scripts
Step1: setInterval function is called every 1000ms (1s)
Stpe2: In that function. Increment the seconds
Step3: Check the Conditions
<span id="count-up">0:00</span>
<script>
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function(){
countUp();
}, 1000);
function countUp () {
second++;
if(second == 59){
second = 00;
min = min + 1;
}
if(second == 10){
zeroPlaceholder = '';
}else
if(second == 00){
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min+':'+zeroPlaceholder+second;
}
</script>
Check out these solutions:
Compute elapsed time
Just wanted to put my 2 cents in. I modified #Ajay Singh's function to handle countdown and count up Here is a snip from the jsfiddle.
var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
runClock(function(){
console.log('done');
clearInterval(t);
},function(timeElapsed, timeRemaining){
console.log( timeElapsed.seconds );
}, countDown);
}, 100);
https://jsfiddle.net/3g5xvaxe/
Here is an React (Native) version:
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class CountUp extends Component {
state = {
seconds: null,
}
get formatedTime() {
const { seconds } = this.state;
return [
pad(parseInt(seconds / 60)),
pad(seconds % 60),
].join(':');
}
componentWillMount() {
this.setState({ seconds: 0 });
}
componentDidMount() {
this.timer = setInterval(
() => this.setState({
seconds: ++this.state.seconds
}),
1000
);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<View>
<Text>{this.formatedTime}</Text>
</View>
);
}
}
function pad(num) {
return num.toString().length > 1 ? num : `0${num}`;
}
Here is one using .padStart():
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<title>timer</title>
</head>
<body>
<span id="minutes">00</span>:<span id="seconds">00</span>
<script>
const minutes = document.querySelector("#minutes")
const seconds = document.querySelector("#seconds")
let count = 0;
const renderTimer = () => {
count += 1;
minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
seconds.innerHTML = (count % 60).toString().padStart(2, "0");
}
const timer = setInterval(renderTimer, 1000)
</script>
</body>
</html>
From MDN:
The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
This is how I build timerView element which does not confuse by calling function many times.
function startOTPCounter(countDownDate){
var countDownDate = '21/01/2022 16:56:26';//Change this date!!
var x = setInterval(function() {
var now = new Date().getTime();
var distance = moment(countDownDate, 'DD/MM/YYYY hh:mm:ss').toDate().getTime() - now;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timerView").innerHTML = minutes + "min " + seconds + "sn";
if (distance < 0) {
clearInterval(x);
// document.location.reload();
document.getElementById("timerView").innerHTML = "Expired!";
}
}, 1000);
if(window.preInterval != undefined){
clearInterval(window.preInterval);
}
window.preInterval = x;
//if(sessionStorage.preInterval != undefined){
// clearInterval(sessionStorage.preInterval);
//}
//sessionStorage.preInterval = x;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<html>
<head>
</head>
<body>
<div>
<p style="color:red; font-size: 15px; text-align:center; " id='timerView'></p>
<input type="button" name="otpGonder" value="Send Again" class="buton btn btn-default " onclick="startOTPCounter()" id="otpGonder">
</div>
</body>
</html>

Categories

Resources