How to Change the display of countdown? - javascript

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()

Related

how to display " backward timer " using JavaScript?

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

Create a countdown timer on button click when value is entered in text box : Javascript

I meet a problem like when I try to enter a number like 30, and count it down until 0, but it doesn't work.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script type="text/javascript">
function startTimer()
{
seconds = seconds - 1;
if (seconds <= 0)
{
seconds = 0;
}
else
{
seconds--;
}
var obj = document.getElementById("timer");
obj.display.value= seconds;
}
</script>
</head>
<body>
<form id="timer" action="#">
<p><input type="text" name="display" size="
20" /></p>
<p><input type="button" value="Start"
onclick="Id=setInterval('startTimer()', 100)" />
</form>
</script>
</body>
</html>
I think the problem is in if else statement, I am not sure if I make the user input correct.
Just assign 'seconds' to the current value of obj.display.value at he start of startTimer() and make sure to give the seconds input a 'number' type and a starting value.
Also use clearInterval(Id) to stop the timer once its finished..
function startTimer()
{
var obj = document.getElementById("timer");
/* make sure to tell javascript that 'seconds' is Number that
comes from the input box */
var seconds;
seconds = Number(obj.display.value);
/* Don't need this *AND* seconds-- */
// seconds = seconds - 1;
if (seconds <= 0)
{
clearInterval(Id);
seconds = 0;
}
else
{
seconds--;
}
obj.display.value = seconds;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script type="text/javascript">
</script>
</head>
<body>
<form id="timer" action="#">
<p><input type="number" name="display" size="
20" value="30" /></p>
<!-- changed the interval from 100ms to 1000ms -->
<p><input type="button" value="Start"
onclick="Id=setInterval('startTimer()', 1000)" />
</form>
</script>
</body>
</html>
You can use something like this:
modify the number to whatever you want, if you want an input control then I assume you know how to do it, if not let me know.
function myFunction() {
var inputVal = document.getElementById('myInput').value;
var seconds = inputVal, $seconds = document.querySelector('#countdown');
(function countdown() {
$seconds.textContent = seconds + ' second' + (seconds == 1 ? '' : 's')
if(seconds --> 0) setTimeout(countdown, 1000)
})();
}
<input type="text" id="myInput" placeholder="Enter number..." >
<button onclick="myFunction()">Start Counter</button>
<span id="countdown"></span>
asign seconds at the top of the code...
<script type="text/javascript">
seconds =100;
<input type="number" id="inp">
<div id="counter"></div>
<script>
let input = document.getElementById('inp')
let counter = document.getElementById('counter')
let handleInput = e => {
let num = Number(e.target.value)
let _counter = num - 1
let timer = setInterval(_ => {
if(!_counter)
clearInterval(timer)
counter.innerText = _counter
_counter--
}, 1000)
}
input.addEventListener('input', handleInput)
</script>
The above logic works for 1 - 9 (single-digit input), you can add a debounce if you want to go for double-digit or greater numbers

Why my InnerHTML code won't display any data in the form fields?

I made a simple change calculator. After playing with the code, I managed to make it calculate the values I needed but I can't make it populate my form. If I use alert, the function is right but if I try to use innerHTML to fill the fields, nothing happens. I am really stuck on this one. :(
var quarters;
var dimes;
var nickels;
var pennies;
function Calculate() {
if (cents >= 25) {
quarters = Math.floor(cents / 25);
var qreminder = cents % 25;
if (qreminder <= 24) {
dimes = Math.floor(qreminder / 10);
var dreminder = qreminder % 10;
}
if (dreminder < 10) {
nickels = Math.floor(dreminder / 5);
var nreminder = dreminder % 5;
}
if (nreminder < 5) {
pennies = nreminder / 1;
}
document.getElementById("quarters").innerHTML = quarters;
document.getElementById("dimes").innerHTML = dimes;
document.getElementById("nickels").innerHTML = nickels;
document.getElementById("pennies").innerHTML = pennies;
}
if (cents < 25) {
quarters = Math.floor(cents / 25);
var qreminder = cents % 25;
if (qreminder <= 24) {
dimes = Math.floor(qreminder / 10);
var dreminder = qreminder % 10;
}
if (dreminder < 10) {
nickels = Math.floor(dreminder / 5);
var nreminder = dreminder % 5;
}
if (nreminder < 5) {
pennies = nreminder / 1;
}
document.getElementById("quarters").innerHTML = quarters;
document.getElementById("dimes").innerHTML = dimes;
document.getElementById("nickels").innerHTML = nickels;
document.getElementById("pennies").innerHTML = pennies;
}
}
var cents = document.getElementById("cents").value;
document.getElementById("calculate").addEventListener("click", Calculate);
<div id="content">
<h1>Change Calculator</h1>
<label>Enter number of cents (0-99):</label>
<input type="text" id="cents" />
<input type="button" value="Calculate" name="calculate" id="calculate" /><br />
<p> </p>
<label>Quarters:</label>
<input type="text" id="quarters" class="disabled" disabled="disabled" /><br />
<label>Dimes:</label>
<input type="text" id="dimes" class="disabled" disabled="disabled" /><br />
<label>Nickels:</label>
<input type="text" id="nickels" class="disabled" disabled="disabled" /><br />
<label>Pennies:</label>
<input type="text" id="pennies" class="disabled" disabled="disabled" /><br />
<p> </p>
Setting the .innerHTML property of <input> types will not do anything. Instead, set the .value property of those elements.
document.getElementById("quarters").value = quarters;
document.getElementById("dimes").value = dimes;
document.getElementById("nickels").value = nickels;
document.getElementById("pennies").value = pennies;

How to put Stop and Reset button in html and javascript

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

Countdown timer is not running

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.

Categories