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="";
}
Related
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>
I'm creating an appointment form. I'm trying to retrieve the hour and minute using $_POST['minute'] but I kept getting "Undefined variable or index".
HTML
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
<h5>Schedule your 15 minute consultation</h5>
<p id="date">MM/DD/YYYY</p>
<div id="time">
<select id="hours" name="hour"></select>
<span>:</span>
<select id="minutes" name="minute"></select>
<div id="timeLabel">
<label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
</div>
</div>
<input placeholder="Name" name="name" id="name" />
<input placeholder="Email" name="email" id="email" />
<button class="submitBtn" name="submitBtn">SUBMIT</button>
<p id="isSent"></p>
</form>
JS
const hours = document.getElementById("hours");
for (let i = 1; i <= 12; i++) {
hours.innerHTML += `<option value="${i}">${i}</option>`;
}
const minutes = document.getElementById("minutes");
for(let i = 0; i <= 45; i+=15) {
if(i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
function ajaxSubmit() {
let name = document.getElementById('name'),
email = document.getElementById('email'),
date = document.getElementById('date'),
hours = document.getElementById('hours'),
minutes = document.getElementById('minutes'),
am = document.getElementById('am'),
pm = document.getElementById('pm');
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.querySelector("#isSent").innerHTML = xhr.responseText;
}
}
xhr.open('POST', 'mail.php?', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=" + name.value +
"&email=" + email.value +
"&date=" + date.value +
"&hours=" + hours.value +
"&minutes=" + minutes.value +
"&am" + am.value +
"&pm" + pm.value);
}
I've tried $hour = $_POST['hour']; but that did not work, same with the minute. So here's my PHP
$hour = null;
$minute = null;
if(isset($_POST['hour'])) {
$hour = $_POST['hour'];
}
if(isset($_POST['minute'])) {
$minute = $_POST['minute'];
}
The issue is the way you are sending form data to PHP. Better way of doing is to use new FormData() function of Javascript. It sends the serialized data so no additional processing is needed.
const hours = document.getElementById("hours");
for (let i = 1; i <= 12; i++) {
hours.innerHTML += `<option value="${i}">${i}</option>`;
}
const minutes = document.getElementById("minutes");
for (let i = 0; i <= 45; i += 15) {
if (i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
function ajaxSubmit() {
var form = document.querySelector('form');
var data = Object.fromEntries(new FormData(form));
console.log(data)
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.querySelector("#isSent").innerHTML = xhr.responseText;
}
}
xhr.open('POST', 'mail.php?', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
<h5>Schedule your 15 minute consultation</h5>
<p id="date">MM/DD/YYYY</p>
<div id="time">
<select id="hours" name="hour"></select> <span>:</span>
<select id="minutes" name="minute"></select>
<div id="timeLabel">
<label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
</div>
</div>
<input placeholder="Name" name="name" id="name" />
<input placeholder="Email" name="email" id="email" />
<button class="submitBtn" name="submitBtn">SUBMIT</button>
<p id="isSent"></p>
</form>
Change your $_POST from hour to plural hours, the same with minute to minutes.
$hours = null;
$minute = null;
if(isset($_POST['hours'])) {
$hours = $_POST['hours'];
}
if(isset($_POST['minutes'])) {
$minutes = $_POST['minutes'];
}
//this message will display on #isSent paragraph
if(isset($hours) and isset($minutes))
echo "your Schedule 15 minute consultation($hours:$minutes) has been registered!";
Tip: for javascript generating readable time format use padStart function:
for(let i = 0; i <= 45; i+=15) {
minutes.innerHTML += `<option value="${(''+i).padStart(2,'0')}">${(''+i).padStart(2,'0')}</option>`;
}
Insead of if else statement condition.
for(let i = 0; i <= 45; i+=15) {
if(i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
I have made a countdown with password protection. So this is my code
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 180;
var pass1 = 12;
var input = document.getElementById("userInput").value;
function myClock() {
if (input==pass1){
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
alert("Reached zero");
}
}
}
}
<p id="demo">180</p>
<form id="form" onsubmit="return false;">
<input type="password" id="userInput" />
<br/>
<input type="submit" onclick="clock()" value="Start"/>
<button onclick="clearInterval(myTimer)">Stop counter</button>
</form>
And this is the result.
But i dont like like that. I want to change into minutes. So 180 will be 3 minutes 0 seconds. And still countdown until 0 minute 0 second. How to change it?
This can be achieved by small modifications in existing code. You need to calculate mins and remaining seconds from seconds. Refer following code sample.
const mins = Math.floor(c / 60);
const remainingSecs = c % 60;
Integrating everything:
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 180;
var pass1 = 12;
var input = document.getElementById("userInput").value;
function myClock() {
if (input == pass1) {
c = parseInt(c);
if (!isNaN(c) || c > 0) {
c--;
const mins = String(Math.floor(c / 60)).padStart(2, '0');
const remainingSecs = String(c % 60).padStart(2, '0');
document.getElementById("demo").innerHTML = `${mins}:${remainingSecs}`;
if (c === 0) {
clearInterval(myTimer);
alert("Reached zero");
}
}
}
}
}
<p id="demo">Timer will appear here</p>
<form id="form" onsubmit="return false;">
<input type="password" id="userInput" />
<br />
<input type="submit" onclick="clock()" value="Start" />
<button onclick="clearInterval(myTimer)">Stop counter</button>
</form>
String.prototype.padStart()
i have no idea how to save and show out put next to stopwatch:
00:01:30 , 00:01:30 something like this.
its not important but can i make stopwatch to stop on some time like 45 min
i created a button "save" was playing whit code but i have no idea how to make it save output and show
i was trying to find in internet but could not find
I appreciate any help.
var ss = document.getElementsByClassName('stopwatch');
[].forEach.call(ss, function(s) {
var currentTimer = 0,
interval = 0,
lastUpdateTime = new Date().getTime(),
start = s.querySelector('button.start'),
stop = s.querySelector('button.stop'),
reset = s.querySelector('button.reset'),
mins = s.querySelector('span.minutes'),
secs = s.querySelector('span.seconds'),
cents = s.querySelector('span.centiseconds');
start.addEventListener('click', startTimer);
stop.addEventListener('click', stopTimer);
reset.addEventListener('click', resetTimer);
function pad(n) {
return ('00' + n).substr(-2);
}
function update() {
var now = new Date().getTime(),
dt = now - lastUpdateTime;
currentTimer += dt;
var time = new Date(currentTimer);
mins.innerHTML = pad(time.getMinutes());
secs.innerHTML = pad(time.getSeconds());
cents.innerHTML = pad(Math.floor(time.getMilliseconds() / 10));
lastUpdateTime = now;
}
function startTimer() {
if (!interval) {
lastUpdateTime = new Date().getTime();
interval = setInterval(update, 1);
}
}
function stopTimer() {
clearInterval(interval);
interval = 0;
}
function resetTimer() {
stopTimer();
currentTimer = 0;
mins.innerHTML = secs.innerHTML = cents.innerHTML = pad(0);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
</head>
<body>
<h1>Stopwatch</h1>
<div class="stopwatch">
<div class="controls">
<button class="start">Start</button>
<button class="stop">Stop</button>
<button class="reset">Reset</button>
<button class="save">save</button>
</div>
<div class="display">
<span class="minutes">00</span>:<span class="seconds">00</span>:<span class="centiseconds">00</span>
</div>
</div>
<script src="stopwatch.js"></script>
</body>
</html>
if i correct understand - here is solution. You still need some validations on input fields, checks on current timer and ithers, but it's worked version if user takes into account all these nuances himself.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Stopwatch</title>
</head>
<body>
<h1>Stopwatch</h1>
<div class="stopwatch">
<div class="controls">
<button class="start">Start</button>
<button class="stop">Stop</button>
<button class="reset">Reset</button>
||stop on:
<input class="min" placeholder="min" type="text" style="width: 30px" />:
<input class="sec" placeholder="sec" type="text" style="width: 30px" />:
<input class="ms" placeholder="ms" type="text" style="width: 30px" />
<button class="save">save</button>
<div class="savedTimeBlock" style="display: none">
saved time:
<div style="display: inline-block" class="time"></div>
</div>
</div>
<div class="display">
<span class="minutes">00</span>:<span class="seconds">00</span>:<span
class="centiseconds"
>00</span
>
</div>
</div>
<script src="stopwatch.js"></script>
</body>
</html>
stopwatch.js
var ss = document.getElementsByClassName("stopwatch");
[].forEach.call(ss, function(s) {
var currentTimer = 0,
interval = 0,
lastUpdateTime = new Date().getTime(),
timeToStop = {
min:null,
sec:null,
ms:null
},
start = s.querySelector("button.start"),
stop = s.querySelector("button.stop"),
reset = s.querySelector("button.reset"),
mins = s.querySelector("span.minutes"),
secs = s.querySelector("span.seconds"),
cents = s.querySelector("span.centiseconds"),
minutes = s.querySelector(".min"),
seconds = s.querySelector(".sec"),
milliseconds = s.querySelector(".ms"),
savedTimeBlock = s.querySelector(".savedTimeBlock"),
time = s.querySelector(".time"),
save = s.querySelector(".save");
start.addEventListener("click", startTimer);
stop.addEventListener("click", stopTimer);
save.addEventListener("click", saveStopTime);
reset.addEventListener("click", resetTimer);
function pad(n) {
return ("00" + n).substr(-2);
}
function saveStopTime() {
let min = timeToStop.min = pad(+minutes.value),
sec = timeToStop.sec = pad(+seconds.value),
ms = timeToStop.ms = pad(+milliseconds.value);
if (+min || +sec || +ms) {
showSavedTimeBlock(min, sec, ms)
} else {
killSavedTimeBlock()
}
}
const showSavedTimeBlock = (min, sec, ms) => {
savedTimeBlock.style.display = 'inline-block';
time.innerText = `${min}:${sec}:${ms}:`
};
const killSavedTimeBlock = () => {
savedTimeBlock.style.display = 'none';
timeToStop.min = null;
timeToStop.sec = null;
timeToStop.ms = null;
time.innerText = ''
};
function update() {
var now = new Date().getTime(),
dt = now - lastUpdateTime;
currentTimer += dt;
var time = new Date(currentTimer);
let min = pad(time.getMinutes());
let sec = pad(time.getSeconds());
let ms = pad(Math.floor(time.getMilliseconds() / 10));
mins.innerHTML = min;
secs.innerHTML = sec;
cents.innerHTML = ms;
let ts = timeToStop;
if (ts.min === min && ts.sec === sec && ts.ms === ms) {
stopTimer()
} else {
lastUpdateTime = now;
}
}
function startTimer() {
if (!interval) {
lastUpdateTime = new Date().getTime();
interval = setInterval(update, 1);
}
}
function stopTimer() {
clearInterval(interval);
interval = 0;
}
function resetTimer() {
stopTimer();
killSavedTimeBlock()
currentTimer = 0;
mins.innerHTML = secs.innerHTML = cents.innerHTML = pad(0);
}
});
OK thanks all. The problem is solved after i see comment.
My countdown timer is not running.
<script type="text/javascript">
function timer(){
var count = document.getElementById("numb").value;
var counter=setInterval(timer, 1000);
var detik = count;
do {
count--;
document.getElementById("timer").innerHTML=count + " secs";
if (count<=0) {
count = detik+1;
}
} while (count===detik+1);
}
</script>
<input type="text" id="numb" name="numb" value=""></input>
<input type="button" value="click" onClick="timer();"/>
<span id="timer"></span>
There were some logic problem with your timer function. Check this fiddle.
HTML
<input type="text" id="url" name="url" value=""></input>
<input type="button" value="click" onClick="timer();" />
<span id="timer"></span>
JavaScript
function timer() {
clearInterval(counter);
var count = parseInt(document.getElementById("url").value);
document.getElementById("timer").innerHTML = count + " secs";
var counter = setInterval(function () {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML = count + " secs";
}, 1000);
};
There is a logical error in your code. Say, you gave 5 as input and clicked the button.
The count stores 5 and so is detik.
Inside the do-while loop, the count is decremented,(now 4). Then this is being displayed to the screen. The if condition isn't satisfied. But the do-while condition is also not true. Hence it comes out of the loop.
This whole process repeats again since you have setInterval for the function. On the whole you see the counter remaining the same.
What you need to do is this:
HTML:
<input type="text" id="numb" name="numb" value=""></input>
<input type="button" value="click" onClick="start_timer();"/>
<span id="timer"></span>
JS:
var count;
var intrv;
function start_timer(){
count = document.getElementById("numb").value;
count = parseInt(count);//convert to int..
intrv = setInterval(timer, 1000);
}
function timer(){
document.getElementById("timer").innerHTML = count + " secs";
count--;
if(count<0)
{
clearInterval(intrv);
}
}
JAVASCRIPT
var count = 0;
var inter;
function timer1(flag){
if(flag == 1)
{
count = document.getElementById("url").value;
console.log(count);
flag = 0;
}
count--;
document.getElementById("timer").innerHTML= count + " secs";
if(count<=0){
clearTimeout(inter);
}else{
inter = setTimeout(function(){timer1(0)},1000);
}
}
HTML
<input type="text" id="url" name="url" value="">
<input type="button" value="click" onclick="timer1(1);"/>
<div id="timer"></div>
I changed it like this and it works:
window.timer = function timer() {
var count = document.getElementById("numb").value;
var cTimer = document.getElementById("timer").innerHTML;
if(cTimer && !isNaN(parseInt(cTimer))) cTimer = parseInt(cTimer) - 1;
else cTimer = count;
if(cTimer==0) return;
document.getElementById("timer").innerHTML = cTimer + " secs";
setTimeout(timer, 1000);
}
and this your working DEMO.