i'm making a basic timer, is one of my first projects, when you press a button the code should create 3 different variables that obtain the values from their respective inputs, this 3 symbolize hours, minutes and seconds.
what happens is that if you console.log any of this 3 variables you get that is undefined for some reason, if you don't have this values the entire countdown will not work.
the inputs are set to start at value = 0 in the html, so it's supposed to at least return 0, not undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="title-container">
<div class="title"><h1>vamos a meditar un poco...</h1> </div>
</div>
<div class="timer-container">
<div class="screen-timer"><h2></h2></div>
<input type="number" min="0" max="60" value="0" id="hours">
<input type="number" min="0" max="60" value="0" id="minutes">
<input type="number" min="0" max="60" value="0" id="seconds">
</div>
<div class="button-container">
<button class="btn">Iniciar</button>
</div>
<script src="app.js"></script>
here is the javascript code:
let button = document.querySelector(".btn");
let title = document.querySelector(".title");
let screenTimer = document.querySelector(".screen-timer");
//quotes
let quotes = ["OM MANI PADME HUM", "OM", "BUENOS PENSAMIENTOS, BUENAS PALABRAS, BUENAS ACCIONES", "YO FLUYO COMO EL AGUA"];
//timer start button
button.addEventListener("click", function(){
//time units
let h = document.getElementById("hours").value;
let m = document.getElementById("minutes").value;
let s = document.getElementById("seconds").value;
//title changer
let index = parseInt((Math.random() * quotes.length));
title.innerHTML = `<div class="title"><h1>${quotes[index]}</h1></div>`;
//interval for the timer
let intervalId = setInterval(timer, 1000);
//timer
function timer(){
if(m > 0 && s <= 59){
s--;
} else if(m > 0 && s == 0){
m--;
s = 59;
} else if (h > 0 && m == 0 && s == 0){
h--;
m = 59;
s = 59;
}
if (h === 0 && m === 0 && s === 0){
clearInterval(intervalId)
}
}
//show the timer on the screen
screenTimer.innerHTML = `<div class="screen-timer"><h2> ${h + ":" + m + ":" + s} </h2></div>`
console.log(h);
console.log(m);
console.log(s);
console.log(h.value);
console.log(m.value);
console.log(s.value);
});
i saw other solutions where people write document.getElementById(id).onClick instead of using addEventListener("click", ...) for making the button work when its clicked on, but i think it's the same
You are accessing the values for hours, minutes, and seconds correctly here,
let h = document.getElementById("hours").value;
let m = document.getElementById("minutes").value;
let s = document.getElementById("seconds").value;
And they are giving correct results in your console logs as well,
console.log(h);
console.log(m);
console.log(s);
What you are doing wrong is then trying to access the .value property of these three variables which doesn't exist and that is why undefined is getting printed.
Use h, m, s variables for your output.
The first three console.logs yield the correct results.
console.log(h);
console.log(m);
console.log(s);
These are already the values themselves not the domnodes.
console.log(h.value);
console.log(m.value);
console.log(s.value);
When you try to access the property "value" on the values themselves the result is undefined.
Related
I need to write a function to validate the time of user input from console. The format of the time is HH:mm in 24 hours time.
function isValidTime(timeString) {
var regex_time = /^\d{2}\:\d{2}$/;
if(!regex_time.test(timeString))
{
return false;
}
var hour = timeString.getHour();
var minute = timeString.getMinutes();
if ((hour > 0 && hour <= 23) && (minute > 0 && minute <= 59)) {
return true;
}
}
This is the code I have so far. When I input 5:01, the output is invalid format. When I input 17:01, it shows
node:internal/readline/emitKeypressEvents:71
throw err;
^
TypeError: timeString.getHour is not a function
Could you please help with this function, I am reading user input with readline.
I suggest you use capture groups in the regular expression... And the match method.
Match will return null if no match at all
or an array containing the full match at position 0 followed by all capture group results.
function isValidTime(timeString) {
const regex_time = /^(\d{2})\:(\d{2})$/; // Use capture groups
const timeMatches = timeString.match(regex_time)
if(!timeMatches){
return false
}
const hour = parseInt(timeMatches[1])
const minute = parseInt(timeMatches[2])
return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59
}
console.log(isValidTime("5:01")) // false
console.log(isValidTime("17:05")) // true
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div>
<input type="text" placeholder="MM" id="month">
<input type="text" placeholder="DD" id="date">
<input type="text" placeholder="YYYY" id="year">
<button>Check</button>
<h1>Result</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="script.js"></script>
</body>
</html>
let btnCheck = document.querySelector('button');
let inputMonth = document.querySelector('#month');
let inputDate = document.querySelector('#date');
let inputYear = document.querySelector('#year');
let result = document.querySelector('h1');
btnCheck.addEventListener('click', (event) => {
let month = inputMonth.value;
let year = inputYear.value;
let date = inputDate.value;
// true in the end, so that our date string and date format should match exactly - in moment js it is called Strict Parsing
result.innerText = moment(`${month}/${date}/${year}`, 'MM/DD/YYYY', true).isValid();
});
Solution :
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hour = today.getHours (
var minutes = today.getMinutes
Another Tip :
If you Get A Another Error you can write
var today = new Date();
var parag = document.getElementById("date")
var time = today.getHours () + ":" + today.getMinutes () + ":" + today.getSeconds();
parag.innerHTML = time
i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`
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
I've started to learn JavaScript, and I'm coding a program that get a number from the user and counts down to zero with a delay of one second for each number.
This is my code:
function DescreasNo(){
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
for ( var i=MyInput ; i>0 ; i--){
output.innerHTML += i +"<br>";
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="StyleSheet.css" />
<script src="Script.js"></script>
<title>EyeProctect Project</title>
</head>
<body>
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>
</body>
</html>
I used setTimeout and setInterval, but my problem is that it just shows zeros for each number, like this:
0, 0, 0, 0
Please help me to solve this problem.
You can use setTimeout() with IIFE:
function DescreasNo(){
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
(function loop (i) {
setTimeout(function () {
output.innerHTML += i +"<br>";
if (--i) loop(i); // call the function until end
}, 1000); // 1 second delay
})(MyInput);
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>
You're probably misunderstanding how to user a closure along with setTimeout (or setInterval).
function decreaseNumber() {
const total_hours = parseInt(document.getElementById('HoursOfWork').value);
const output_div = document.getElementById('output01');
let current_hour = total_hours;
const countdown = () => {
output_div.innerHTML += current_hour + "<br />";
if (--current_hour > 0) {
setTimeout(countdown, 1000); // 1000 milliseconds
}
};
countdown();
}
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="StyleSheet.css" />
<script src="Script.js"></script>
<title>EyeProctect Project</title>
</head>
<body>
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="decreaseNumber()">Let's Go!</button>
<p id="output01"></p>
</body>
</html>
With setInterval you could do it like this.
function DescreasNo(){
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
var countDown = MyInput;
var intervalId = setInterval(function () {
output.innerHTML += countDown +"<br>";
if (--countDown <= 0)
clearInterval(intervalId); // clear timer when finished
}, 1000); // 1 second delay between decrements
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>
I would do this with a setInterval you can allow fractional hours if you use parseFloat instead of parseInt. You can also format the seconds fairly easily to give a nice readout.
You should be careful about clearing the interval too incase someone presses the button more than once during the countdown otherwise you will get multiple timers. Here if you press twice it resets it.
Some improvements would include validating input to make sure it's a number:
let int;
function DescreasNo() {
clearInterval(int) // clear interval to allow button to reset counter
var MyInput = document.getElementById('HoursOfWork').value;
let seconds = (parseFloat(MyInput) * 60 * 60)
var output = document.getElementById('output01');
int = setInterval(() => {
if (seconds <= 0) { // finished
clearInterval(int)
return
}
output.innerHTML = formatTime(seconds--)
}, 1000)
}
function formatTime(seconds) {
let hours = Math.floor(seconds / (60 * 60)).toString().padStart(2, '0')
let minutes = Math.floor((seconds - hours * 3600) / 60).toString().padStart(2, '0');
let second = Math.floor(seconds - (hours * 3600) - (minutes * 60)).toString().padStart(2, '0');
return `${hours}:${minutes}:${second}`;
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()">Let's Go!</button>
<p id="output01"></p>
thanks for helping!
The main goal of this is Stop the timer. But It does not work.
I know that this does not work because I am calling a local variable from another function but If I declare the variable as global the setTime starts automatically and It is not what I want.
How could a solve it, or another alternative? thanks!!
This is my code:
var interval2;
function startTimef(){
var startTime = Date.now();
interval2 = setInterval(function() {
var elapsedTime = Date.now() - startTime - 5000;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 75);
}
function myStopFunction(interval2) {
clearInterval(interval2); // does not work because interval2 is a local variable in StartTime.
var result = document.getElementById("result");
var score = document.getElementById("timer").textContent;
if (score < -0.200) { result.innerHTML = score+" Almost there ";}
if (score < -500 && score < -0.200) { result.innerHTML = "Almost there";}
if (score > -0.200 && score < 0 ) { result.innerHTML = "No too bad mate";}
if (score > -0.100 && score < 0.200 ) { result.innerHTML = "Perfect !!!";}
if (score > 0.200 ) { result.innerHTML = "You need some work!";}
};
// Press Enter Keyboard
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TimeOver</title>
</head>
<body>
<div class="main-box">
<h2>Try to Stop the timer as close as possible to cero</h2>
<p id="timer">0000</p>
<button id="stop" onclick="myStopFunction()" >Stop time</button>
<span id="result"></span>
<button id="" onclick="startTimef()" >start</button>
</div>
<script src="main.js"></script>
</body>
</html>
Try this. Removing interval2 from myStopFunction(interval2) will work.
Your first approach will not since you have 2 interval2 variables and JS will use the locally declared interval2 instead of the outer interval2.
var interval2;
function startTimef(){
var startTime = Date.now();
interval2 = setInterval(function() {
var elapsedTime = Date.now() - startTime - 5000;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 75);
}
function myStopFunction() {
clearInterval(interval2);
var result = document.getElementById("result");
var score = document.getElementById("timer").textContent;
if (score < -0.200) { result.innerHTML = score+" Almost there ";}
if (score < -500 && score < -0.200) { result.innerHTML = "Almost there";}
if (score > -0.200 && score < 0 ) { result.innerHTML = "No too bad mate";}
if (score > -0.100 && score < 0.200 ) { result.innerHTML = "Perfect !!!";}
if (score > 0.200 ) { result.innerHTML = "You need some work!";}
};
// Press Enter Keyboard
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TimeOver</title>
</head>
<body>
<div class="main-box">
<h2>Try to Stop the timer as close as possible to cero</h2>
<p id="timer">0000</p>
<button id="stop" onclick="myStopFunction()" >Stop time</button>
<span id="result"></span>
<button id="" onclick="startTimef()" >start</button>
</div>
<script src="main.js"></script>
</body>
</html>