I have a setInterval in my HTML/Javascript document.
Now, as far as I am aware, the setInterval part is typed out exactly as it is in another document of mine, and it works perfectly there. But in this the interval is not repeating every 1 second. It runs it once, then stops. Are there any blatant errors that I am missing?
<html>
<head>
<title>Time</title>
</head>
<body>
<p id="line-one" />
<p id="line-two" />
<p id="line-three" />
<p id="line-four" />
<p id="seconds" />
<SCRIPT type='text/JavaScript'language='JavaScript'>
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var nIntervId;
function counter()
{
if (typeof(nIntervId) != "undefined") {
clearInterval(nIntervId);
}
nIntervId = setInterval(changeASCII, 1000);
}
function changeASCII()
{
document.getElementById("seconds").innerHTML = second;
switch(second) {
case 00:
document.getElementById("line-one").innerHTML = " ___...___ ";
document.getElementById("line-two").innerHTML = "|...|.|...|";
document.getElementById("line-three").innerHTML = "|.|.|.|.|.|";
document.getElementById("line-four").innerHTML = "|___|.|___|";
break;
case 01:
document.getElementById("line-one").innerHTML = " ___ ___";
document.getElementById("line-two").innerHTML = "| | |_ |";
document.getElementById("line-three").innerHTML = "| | | _| |_";
document.getElementById("line-four").innerHTML = "|___| |_____|";
break;
default:
document.getElementById("line-one").innerHTML = "Nothing";
document.getElementById("line-two").innerHTML = "To";
document.getElementById("line-three").innerHTML = "See";
document.getElementById("line-four").innerHTML = "Here";
break;
}
}
window.onload = counter();
</SCRIPT>
</body>
</html>
Everything is fine, although, You do not update real value of second hence You get it from date, which also is not updated.
Check this out in fiddle;
http://jsfiddle.net/H8C4W/
function changeASCII()
{
now=new Date();
second=now.getSeconds();
...
Related
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 am building a project to help kids in school learn how to read faster. I have borrowed bits of code here and there and mixed up a timer and text generator.
Now I am trying to build a function to generate a summary of the latest reading time (so that they can see progress), perhaps in the form of <ol>, I guess I need to iterate over an array, push into it and then display but none of that seems to work.
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = "";
m = checkTime(m);
if (h > 12) {
h = h - 12;
ampm = " PM";
} else if (h == 12) {
h = 12;
ampm = " AM";
} else if (h < 12) {
ampm = " AM";
} else {
ampm = "PM";
};
if (h == 0) {
h = 12;
}
document.getElementById('display').innerHTML = h + ":" + m + ampm;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
function startDate() {
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()] + " | " + [d.getMonth() + 1] + "/" + d.getDate() + "/" + d.getFullYear();
}
var quotes = ["",
"\"Dude, suckin' at something is the first step at being sorta good at something.\"<br>- Jake <small><em>(Adventure Time)</em></small>",
"\"Either I will find a way, or I will make one.\"<br> - Philip Sidney",
"\"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.\"<br>- Thomas A. Edison",
"\"You are never too old to set another goal or to dream a new dream.\"<br>- C.S Lewis",
"\"If you can dream it, you can do it.\"<br>- Walt Disney",
"\"Never give up, for that is just the place and time that the tide will turn.\"<br>- Harriet Beecher Stowe",
"\"I know where I'm going and I know the truth, and I don't have to be what you want me to be. I'm free to be what I want.\"<br>- Muhammad Ali",
"\"If you always put limit on everything you do, physical or anything else. It will spread into your work and into your life. There are no limits. There are only plateaus, and you must not stay there, you must go beyond them.\"<br>- Bruce Lee",
];
function genQuote() {
var quote = document.getElementById("quote");
var generate = document.getElementById("gen");
generate.addEventListener("click", changeText);
quote.innerHTML = quotes[0];
function changeText() {
var searchTerm = quote.innerHTML;
var index = quotes.indexOf(searchTerm) + 1;
if (index == quotes.length) index = 0;
var result = quotes[index];
quote.innerHTML = result;
return;
}
}
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime;
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
var minutes = Math.round(seconds / 60);
document.getElementById("quote").innerHTML = ("You have read for:" + " " + minutes + " minutes" + " " + seconds + " seconds");
setTimeout(function() {
location.reload();;
}, 5000);
}
function report() {
// results = [];
// times = document.getElementById("quote").innerHTML;
// for (i=0; i <= times.length; i++) {
// results.push(i);
// return results;
// }
}
<div id="display"></div>
<div id="date"></div>
<div id="quote"></div>
<div id="get"></div>
Here is the HTML in case that help:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<title>2 Cool 4 School</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<body onload="startTime(); startDate()">
<div class="container">
<div id="date"></div>
<div id="display"></div>
<div id="content">
<p id="quote">"the people who are crazy enough to think they can change the world are the ones who do." <br/>- Steve Jobs</p>
</div>
</div>
<div id="b-nav">
<ul>
<button id="genone"class="btn btn-outline-primary" onclick="start()">Start</button>
<button id="gen" onclick="genQuote()">Continue reading</button>
<button id="genthree" class="btn btn-outline-success" onclick="report()">History</button>
<button id="gentwo" class="btn btn-outline-secondary" onclick="end()">End</button>
</ul>
</div>
</body>
<script src="script.js"></script>
</html>
Right now when I click Stars the timer runs, when I click End after that I am provided "you have read for: 0 minutes 4 seconds"
I would like to get a report of this something like:
you have read for: 3 minutes 30 seconds
you have read for: 2 minutes 50 seconds
you have read for: 1 minutes 40 seconds
etc Hope that helps(sorry I didnt get the snippet thing)
the biggest problem is placing "return results;" inside your loop. which means your loop never fully executes. move that outside your loop.
secondly, your report() function is just going to return a string of numbers, [0,1,2,3,4...] which is probably not what you are looking for.
I have poured over this code and I feel pretty positive about it. That being said, something is obviously missing, as the program itself comes up with an empty clock when run in the browser. I know that the brackets and parentheses all have a matching set, and I am fairly confident in my functions. The chrome developer tools were unhelpful. Anyone with a good eye for Javascript able to see what is missing here?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec today.getSeconds();
var ap = "AM";
if (hour > 12) {
h = h - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hours);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ap").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
You simply have a lot of (3) typos ...
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
var ap = "AM";
if (hour > 12) {
hour = hour - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hour);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ampm").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
*there are other (non-functional) problems in this code, but since it is not the Q, I'd not change them to keep this answer on point.
I'm working on a project where I need to manipulate time speed forward and backward. This module seems like what I need but I can't get it working:
https://github.com/mattbradley/warpjs/blob/master/README.md
Any help appreciated
<html>
<head>
</head>
<body>
<script src="jquery.min.js"></script>
<script src="warp.js"></script>
<div id="container"></div>
<span id="info"></span><br>
<span id="time"></span>
<span id="time2"></span>
<script>
setInterval(function() {
var now = new Date;
now = Date.warp.clock(true);
//now = Date.warp.speed(2); // DOESNT WORK?
var dateD = [now.getMonth() + 1,now.getDate(),now.getFullYear()];
var dateE = [now.getHours(),now.getMinutes(),now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 20);
</script>
</body>
</html>
The wrap is a static method, it doesn't return any value(undefined is returned)
setInterval(function() {
Date.warp.speed(3);
var now = new Date;
var dateD = [now.getMonth() + 1, now.getDate(), now.getFullYear()];
var dateE = [now.getHours(), now.getMinutes(), now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 1000);
Demo: Fiddle
The problem is that when I put the correct hour and the incorrect minutes it always returns me: "bad" and "very nice". I don't know what is going wrong so could you help me please.
I have the following html and JS:
<!DOCTYPE html>
<html>
<body>
<script language="Javascript">
var d = new Date();
var h = d.getHours();
var h1 = document.forms["INICI"].starthour.value;
var m = d.getMinutes();
var m1 = document.forms["INICI"].startminut.value;
function myHour() {
if ( h==h1 ) {
document.write("nice"+"<br>");
} else {
document.write("bad"+"<br>");
}
}
function myMinut() {
if ( m1==m ){
document.write("very nice"+"<br>");
} else {
document.write("very bad"+"<br>")
}
}
</script>
<form name="INICI">
start hour: <input name="starhour"/> <br />
<br>
start minut: <input name="startminut"/> <br />
<input id="insert1"
onclick="myHour(); myMinut();"
type="submit"
value="Click" />
</form>
</body>
</html>
(I'm new here.... sorry if I did this post very bad)
I had improved your code. here is a working version of it.
<!DOCTYPE html>
<html>
<body>
<form name="INICI">
start hour:
<input name="starthour" />
<br />
<br>
start minut:
<input name="startminut" />
<br />
<input id="insert1" onclick="EvaluateResults()" type="submit" value="Click" />
</form>
<script language="Javascript">
function EvaluateResults() {
var d = new Date();
var h = d.getHours();
var h1 = document.forms["INICI"].starthour.value;
var m = d.getMinutes();
var m1 = document.forms["INICI"].startminut.value;
console.log(h + ' ' + h1);
if (h == h1) {
document.write("nice" + "<br>");
}
else {
document.write("bad" + "<br>");
}
if (m1 == m) {
document.write("very nice" + "<br>");
}
else {
document.write("very bad" + "<br>")
}
}
</script>
</body>
</html>
What went wrong with your code is that you are taking the time when the JavaScript file loaded and executed and not when the button is pressed. What i did to solve your problem is I just created a method and transferred the code that acquires the time.
You are setting your variables when the page loads so they will always be the same.
If you put them inside the functions this could be solved
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
function myHour()
{
var h1 = document.forms["INICI"].starthour.value;
if (h==h1){
document.write("nice"+"<br>");
}
else{
document.write("bad"+"<br>");
}
}
function myMinut()
{
var m1 = document.forms["INICI"].startminut.value;
if (m1==m){
document.write("very nice"+"<br>");
}
else{
document.write("very bad"+"<br>")
}
}
You have a typo:
<input name="starhour"/>
Needed
<input name="starthour"/>
Also put your script tag to the end of the body