Js how to add time counter onclick event - javascript

I'm using a custom video player with html5. I already got the video length contained in custom fields, so it's easy for me to stamp the duration on the player screen.
I just need now to stamp a 00:00:00 (which stands for seconds, minutes and hours) which will start a progressive count as soon as I press play in the video player.
I suppose I should put the command within this line of code:
playButton.addEventListener("click", function(){
if(video.paused==true){
video.play();
}
}
...and then create another script which makes the 00:00:00 be influenced by the addEventListener, but I don't have enough knowledge to create it properly.
Can you kindly help me doing it?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>Time <span id="time">00:00:00</span> </div>
<div><button id="btn">pause</button></div>
<script>
var btn = document.getElementById("btn");
var btnFlag = false;
var timer = 1; // this is global variale
// flag means here play and pause 1 for play 0 for pause
function startTimer(duration, display) {
var mytimer = setInterval(function () {
if (++timer == duration ) {
timer--;
clearInterval(mytimer)
}
$("#btn").off('click').on('click',function(e){
//btn.addEventListener("click",function(e) {
console.log("click")
if(!btnFlag){
console.log("here")
btnFlag = true
clearInterval(mytimer)
$("#btn").text('Play')
}
else{
console.log("pass")
btnFlag = false
startTimer(duration, display)
$("#btn").text('Pause')
}
})
hours = parseInt(timer /3600, 10)
minutes = parseInt((timer % 3600) / 60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":"+ minutes + ":" + seconds;
}, 1000);
}
window.onload = function () {
var timeinsecond = 100,
display = document.querySelector('#time');
startTimer(timeinsecond, display);
};
</script>
</body>
</html>
Try It

Related

Submit the value of a timer which is then use for JS function

I am trying to enable the user to set the value of a timer and then to see the countdown timer displayed on the webpage.
Here is my HTML code:
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" name="submit" class="submit" value="Submit">
And here is my JS code:
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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
jQuery(function ($) {
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
});
This code is working because in the HTML file, I hardcoded the value to 3 minutes directly.
But I would like to remove this value="3"and be able to set it up manually in the input field.
But when I am doing that, the timer is not displayed.
First, you should add the 'id'-attribute to the input element:
<input type="submit" name="submit" class="submit" value="Submit" id="submit">
But just setting the function glitches out the timer if the user inputs multiple values, so you should change your code like this:
var clearIntervalId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
clearIntervalId = 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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
$("#submit").click(function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
if (typeof clearIntervalId !== 'undefined') {
clearInterval(clearIntervalId)
}
startTimer(myVar, display);
});
clearIntervalId is used, so that the previous running setInterval()-function is getting cleared out everytime the user clicks the button, so that there won't be interfering changes in the current minutes + seconds.
What do you need is a trigger for the startTimer function after event
and in your code the event is a button click
Add id attribute to your button
<input type="submit" id="submit" name="submit" class="submit" value="Submit">
and add click event listener to your button
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
jQuery(function ($) {
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
});
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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" id="submit" name="submit" class="submit" value="Submit">

how do i auto-submit the form when the timer comes to 00:00:00

I have used a countdown timer in my online examination website,the timer is shown via javaScript but problem is that after the 00:00:00 the timer shows negative time.I just want to stop the timer at 00:00:00 and submit a form when the time is over.below is the code that accurately displaying me the timer.
<?php
// Upon starting the section
session_start();
$_SESSION['TIMER'] = time() + 600; // Give the user Ten minutes
?>
<script type="text/javascript">
var TimeLimit = new Date('<?php echo date('r', $_SESSION['TIMER']) ?>');
</script>
<script type="text/javascript">
function countdownto() {
var date = Math.round((TimeLimit-new Date())/1000);
var hours = Math.floor(date/3600);
date = date - (hours*3600);
var mins = Math.floor(date/60);
date = date - (mins*60);
var secs = date;
if (hours<10) hours = '0'+hours;
if (mins<10) mins = '0'+mins;
if (secs<10) secs = '0'+secs;
document.body.innerHTML = hours+':'+mins+':'+secs;
setTimeout("countdownto()",1000);
if((hours==00)&&(mins==00)&&(secs==00))
document.alert("time is over");
}
countdownto();
</script>
I assume that your form has an ID attribute with this value yourForm.
// HTML
<form id="yourForm">[...]</form>
// JS
if((hours==00)&&(mins==00)&&(secs==00)) {
document.getElementById('yourForm').submit();
} else {
setTimeout(countdownto, 1000);
}
Note: Remove your setTimeout(countdownto, 1000); before the if statement
Alternative way.
You could kill the timeout with clearTimeout()
var myTimeout = setTimeout(countdownto, 1000);
if((hours==00)&&(mins==00)&&(secs==00)) {
clearTimeout(myTimeout);
document.getElementById('yourForm').submit();
}
clearTimeout documentation
Let's create a index.php file please check it. form submit on timer you can pass time through in javascript CountDown(5,div); function.
<html>
<body>
<form action="" method="post" name="mcQuestion" id="mcQuestion">
Name:<input type="test" name="name" value="Test">
<div><span id="display" style="color:#FF0000;font-size:15px"></span></div>
<div><span id="submitted" style="color:#FF0000;font-size:15px"></span></div>
</form>
<script>
var div = document.getElementById('display');
var submitted = document.getElementById('submitted');
function CountDown(duration, display) {
var timer = duration, minutes, seconds;
var interVal= 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.innerHTML ="<b>" + minutes + "m : " + seconds + "s" + "</b>";
if (timer > 0) {
--timer;
}else{
clearInterval(interVal)
SubmitFunction();
}
},1000);
}
function SubmitFunction(){
submitted.innerHTML="Time is up!";
document.getElementById('mcQuestion').submit();
}
CountDown(5,div);
</script>
</body>
</html>

Format time to minutes and seconds in countdown/timer

I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="num">25 min</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>
<script src="script.js"></script>
</body>
</html>
and here is javascript:
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function countDown(secs, elem) {
var element = document.getElementById(elem);
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
//secs *= 60;
if(secs%60 >= 10){ //10 - if it's not a single digit number
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
}
else{
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
}
element.innerHTML = "Please wait for "+secs+" minutes";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
function increaseNumber() {
secs += 5;
document.getElementById('num').innerHTML = secs + ' min';
}
function decreaseNumber() {
if(secs >= 10) {
secs -= 5;
document.getElementById('num').innerHTML = secs + ' min';
}
}
Is there a reason you're doing it by hand ?
If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.
If you have to do it by hand because of some limitations, what are they ?
For reference:
//Creates a moment. Its value is the time of creation
var timer = moment();
//add 60 seconds to the timer
timer.add(60, 's');
//Removes 1 minutes from the timer
timer.subtract(1, 'm');
Sources :
Add
Substract
Try this countDown function:
function countDown(secs, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" minutes";
var second = 0;
var timer = setInterval(function(){
var extraZero = second < 10 ? '0' : '';
document.getElementById('num').innerHTML = secs + ":" + extraZero + second;
if (second-- === 0) {
second = 59;
if (secs-- === 0){
clearInterval(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
}, 1000);
}
Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

Stopwatch Not working

I found this stopwatch tutorial online, however when i tried implementing it, it kept saying "TypeError: start is null" and "TypeError: h1 is undefined" in the console when i inspect the element. What is bugging me even further is that when i insert the code in here it works and if i put it into notepad++ it does not work. Is there a jquery file that i might have missed during the implementation and some how snippet is making it work?
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
<h1><time>00:00:00</time></h1>
<button id="start" >start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
Wrap all your code, including functions, in a comon function that you could name initialize() { }.
Then, put on your <body> tag the function binded onload event like following :
<body onload="initialize()">
This will tell your code not to execute unless the whole DOM and element have been created, because you can't access your elements unless they are all fully loaded.
Likely, you have defined your Javascript BEFORE your HTML. Remember Javascript is a blocking language, so it will halt all operation (including loading the HTML) until the script is finished.
Move the script below your HTML or use some form of $(document)ready

How do I display millisecond in my stopwatch?

I am implementing a stopwatch by using Javascript. I have basic html document setup and a javascript file called stopwatch.js in which I have the following code. I make use of setInterval function to execute the clockRunning function every 1 second(1000ms). This gives me control over sec, min and hour to increment them accordingly, but I am having difficulty with inserting millisecond into the stopwatch. How should I increment the millisecond from 0 to 1000 and then reset to zero?
I have tried by decreasing the interval time for setInterval function to be called every 1ms and then set millisecond variable to time%1000 in which time variable is increased by 1 every time the function is called. But it does not give the result I want. The millisecond seems to be increasing way too slow.
var running = 0
var time = 0;
var hour = 0;
var min = 0;
var sec = 0;
var millisec = 0;
function start(){
started = window.setInterval(clockRunning, 1000);
}
function stop(){
window.clearInterval(started);
}
function clockRunning(){
time++;
sec++;
if (sec == 60){
min += 1;
sec = 0;
if (min == 60){
hour += 1;
min = 0;
}
}
document.getElementById("display-area").innerHTML = (hour ? (hour > 9 ? hour : "0" + hour) : "00")
+ ":" + (min ? (min > 9 ? min : "0" + min) : "00") + ":" + (sec > 9 ? sec : "0"
+ sec);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<script src="stopwatch.js"></script>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="toggle-button" onClick="start()">Start</button>
<button id="toggle-button" onClick="stop()">Stop</button>
<button id="reset-button">Reset</button>
</div>
</body>
</html>
You should keep track of the starting time then subtract that time from the current time using a Date:
var timeBegan = null
, timeStopped = null
, stoppedDuration = 0
, started = null;
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
}
console.log(stoppedDuration);
started = setInterval(clockRunning, 10);
}
function stop() {
timeStopped = new Date();
clearInterval(started);
}
function reset() {
clearInterval(started);
stoppedDuration = 0;
timeBegan = null;
timeStopped = null;
document.getElementById("display-area").innerHTML = "00:00:00.000";
}
function clockRunning(){
var currentTime = new Date()
, timeElapsed = new Date(currentTime - timeBegan - stoppedDuration)
, hour = timeElapsed.getUTCHours()
, min = timeElapsed.getUTCMinutes()
, sec = timeElapsed.getUTCSeconds()
, ms = timeElapsed.getUTCMilliseconds();
document.getElementById("display-area").innerHTML =
(hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="toggle-button" onClick="start()">Start</button>
<button id="toggle-button" onClick="stop()">Stop</button>
<button id="reset-button" onClick="reset()">Reset</button>
</div>
</body>
</html>
The reason you were seeing the milliseconds "lagging" before was that setInterval is notorious for not firing exactly when you specify. You can get around this using the strategy above.
Update: You could keep track of how long the timer has "paused" between resets. Updated my answer to accommodate this.
complete code here
$(document).ready(function () {
var milliseconds;
var hours;
var minutes;
var seconds;
var interval;
var count = 0;
var lap;
var i = 0;
$(".heading").slideDown("slow"); //slide down heading countdown.
// click function to start timer
$(".start").click(function () {
$(".start").hide();
$(".pause").show(100); // show pause button
$("#end").text("Stopwatch Started"); // change text.
interval = setInterval(newtimer, 10); // run the countdown interval of 1000 millisecond
});
function newtimer() {
hours = parseInt(count * 10 / 1000 / 60 / 60);// calculate hours
minutes = parseInt(count * 10 / 1000 / 60); // calculate minutes
seconds = parseInt((count * 10 / 1000)%60);// calculate seconds
milliseconds = parseInt((count*10) % 1000); // calculate milliseconds
/* display digits in clock manner */
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
count++; // increment in count.
$(".seconds").text(hours + " : " + minutes + " : " + seconds + " : " + milliseconds);
}
/* click function to pause timer*/
$(".pause").click(function () {
$(".start").hide(); //hide start button
$(".restart").hide(); //hide restart button
$(".pause").hide();
$(".resume").show(); // show resume button.
$("#end").text("Stopwatch Paused");
clearInterval(interval); //clear interval will stop the count.
i = i + 1;
lap = " " + hours + " : " + minutes + " : " + seconds + " : " + milliseconds;
$(".lap").append('<p>' + 'Time Lap' + "-" + i + lap + '</p>'); // add p tag in div and count no. of laps.
});
/* click function to resume the countdown */
$(".resume").click(function () {
$("#end").text("Stopwatch Resumed");// change end text.
$(".pause").show();
$(".resume").hide();
interval = setInterval(newtimer, 10);// interval to function new timer. count will remain same where paused.
});
/* click function to stop stopwatch */
$(".stop").click(function () {
$("#end").text("Stopwatch Stopped");
$(".restart").show(); //show restart button
$(".resume").hide(); // hide resume button
$(".start").hide();// hide start button
$(".pause").hide();
$(".lap p").remove(); // remove laps.
clearInterval(interval);
});
/*click function to restart stopwatch*/
$(".restart").click(function () {
$("#end").text("Stopwatch Restarted");// change end text.
$(".restart").hide();
$(".pause").show();
count = 0; // count reset to zero
interval = setInterval(newtimer, 10); //time interval to function new timer
});
/* click function on class reset to reset the countdown */
$(".reset").click(function () {
$(".seconds").text("00 : 00 : 00 : 00"); // set display to initial value.
$(".resume").hide(); // hide resume button
$(".start").show(); // show start button
$(".pause").hide(); // hide pause button
$(".restart").hide(); // hide restart button
$("#end").text(" "); // change end text
$(".lap p").remove(); // remove p tag from div
clearInterval(interval); // clear interval
count = 0; // reset count to initial value.
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>stopwatch</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script></head>
<body style="font-family: cursive;">
<div class="container-fluid clearfix" style="padding:100px; background-color:lightgrey;">
<div style="width:25%; float:left"><img src="./bn.jpg" alt="stopwatch" style="width:100%"></div>
<div class="heading" style="color:#165caa;display:none;margin-left: 365px;font-size: 84px">STOPWATCH</div>
<div class="seconds" style="font-size: 46px;text-align:center;margin-top:30px "> 00 : 00 : 00 : 00</div>
<div style="text-align:center;">
<button class="start mt-3 px-4 btn btn-success">START</button>
<button class="restart mt-3 px-4 btn btn-success" style="display:none">RESTART</button>
<button class="resume mt-3 px-4 btn btn-success" style="display:none">RESUME</button>
<button class="pause mt-3 px-4 btn btn-warning" style="display: none">PAUSE</button>
<button class="stop mt-3 px-4 btn btn-dark">STOP</button>
<button class="reset mt-3 px-4 btn btn-danger">RESET</button>
</div>
<p id="end" style="font-size:32px ;margin-top:30px;text-align:center"></p>
<div class="lap" style="text-align: center; font-size:16px;font-family: monospace;"></div>
</div>
</body>
</html>
BUG FIX!!!
I noticed the Start, Stop, Reset would not work if you hit Start more than once with the code above. I was able to fix this by tweaking the start function!
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}else {
clearInterval(started);
};
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
};
if (stoppedDuration < 1000){
console.log(stoppedDuration+' ms');
};
if (stoppedDuration > 1000){
console.log(stoppedDuration/1000+' seconds');
};
started = setInterval(clockRunning, 10);
return stoppedDuration }

Categories