I've been teaching myself JavaScript and i'm still fairly new, i've tried to make a clock feature to add to my site, however, I can't see to get it to display, this is my full code:
<html>
<head>
<script type="text/javascript">
function tick() {
var hours, minutes, seconds, ap;
var intHours, intMinutes, intSeconds;
var today;
today = new Date();
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
if (intHours == 0) {
hours = "12:";
ap = "Midnight";
} else if (intHours < 12) {
hours = intHours + ":";
ap = "a.m";
} else if (intHours == 12) {
hours = "12:";
ap = "noon";
} else {
intHours = intHours - 12
hours = intHours + ":";
ap = "p.m.";
}
if (intMinutes < 10) {
minutes = "0" + intMinutes + ":";
} else {
minutes = intMinutes + ":";
}
if (intSeconds < 10) {
seconds = "0" + intSeconds + " ";
} else {
seconds = intSeconds + " ";
}
timeString = hours + minutes + seconds + ap;
Clock.innerHTML = timeString;
window.setTimeout("tick();", 100);
}
//--></script>
</head>
<body>
<div id="Clock" align="center" style="font-family: Verdana; font-size: 10px; color:#000000"></div>
</body>
</html>
As I said, I run it and as far as I can see, it should run fine, as I said i'm a bit new, so maybe someone could help me out.
Thanks again people.
EDIT: Before anyone says, I am fully aware that there are premade working examples of this kind of thing, such as jQuery clocks etc, but I wanted to make one myself from scratch.
It is not starting, mainly because you need to call the function at least once initially:
tick();
Where ever you are learning HTML and JavaScript from, stop learning from there immediately; the code habits and methods you are learning are very, very poor and outdated.
Problems include:
not having a DOCTYPE: <!DOCTYPE html>
accessing div#Clock as a global variable Clock, which is deprecated, and should be document.getElementById('Clock');
using a string to setTimeout, when it should really be setTimeout(tick, 100);
using the deprecated align attribute, when you should use text-align: center; in CSS
using the 'old-browser' JavaScript comment-out trick
using inline CSS via the style attribute, which constitutes poor separation of presentation and content
First, you need to run your function tick() somewhere. It doesn't do anything if you only define it. In the body onLoad event for example.
Second, your element should be properly set in a var. You should get the element by id:
var Clock = document.getElementById('Clock');
Just change your last two lines from
window.setTimeout("tick();", 100);
}
to
}
window.setInterval(tick, 1000);
Demo: http://jsfiddle.net/naveen/3PQ8B/1/
Update: missed the document.getElementById part :)
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Related
This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?
(4 answers)
Closed 6 years ago.
I am trying to make a simple web based clock app using pure java-script. I think the general code is right, but I'm not sure how to automatically call the function at a set interval of time. I thought the window.onload, followed by the setInterval method would do this. But it's not automatically updating every half second as I expected. What am I doing wrong?
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow(), 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
Seems to work fine. Just needed to change
window.onload = function() { setInterval( timeNow(), 100); }
to
window.onload = function() { setInterval( timeNow, 100); }
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow, 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
use setInterval(timeNow,100); instead of setInterval(timeNow(),100);
var time, h, m, s, track;
track = 0;
window.onload = function() {
var start = setInterval(timeNow,100);
}
function timeNow() {
var time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; }
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
You are passing an undefined (as the result of calling timeNow) to setInterval. You need to pass the function, so the code will be:
window.onload = function() { setInterval(timeNow, 100); }
I wrote a little browser-game.
The rules are easy: you have 15 seconds to decide if you know the name written on the screen.
You have two buttons: "i know"/"give up" - depends on what you want to choose.
If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.
Whole operation is looped.
Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.
I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<button id= "btnSurrender">give up</button>
<button id= "btnWinning">i know</button>
<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">
var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";
function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}
var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');
var clock = null;
btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);
function timer () {
random_word();
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
pic.innerHTML='<img src="" alt="">';
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
pic.innerHTML='<img src="mops bops.png" alt="">';
}
}, 1000);
}
function surrender(){
clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){
clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
timer();
document.write(randomWord)
setInterval(timer, 17000)
</script>
</body>
</html>
var randomWord;
You need to arrow it at the beginning of the script, before giving a document.write
When I tested your code and set it to the "randomWord" variable at the beginning of the code, it worked; You should do the same, set the variable at the beginning of the code!
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.
I have made a clock in javascript but its a static clock. What changes I need to do in the following code so that it updates with every second.
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>
You can use setInterval to run your clk() function every second:
setInterval(clk, 1000); // run clk every 1000ms
MDN on setInterval
As nnnnnn points out, the timer interval probably won't be synchronized with the passage of an actual, real-time second, so using an interval like 100ms might not be a bad idea.
You can add setTimeout(clk,1000); to your function,as bellow:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk,1000);
}
A JavaScript digital clock from system time, can also manually set. :-)
function timer(h,m,s){
var sec;
var min;
var hrs;
var day;
if(((s<=59) && (s>=0)) && ((m<=59) && (m>=0)) && ((h<=23) && (h>=0))){
sec=s;
min=m;
hrs=h;
//set parent element id 'lga' to your id
var parent = document.getElementById('lga');
parent.innerHTML = '';
var child = document.createElement('div');
child.id = "thanesh";
child.style = 'font-size:20px';
parent.appendChild(child);
setInterval(function(){
sec++;
if(sec==60){sec=0;min++;}
if(min==60){min=0;hrs++;}
if(hrs==24){hrs = 0; min = 0; sec = 0;}
if(hrs<=12){
day = 'AM';
}else{
day = 'PM';
}
document.getElementById('thanesh').innerHTML = '<table style="background-color:#f5f5f5;"><tr><td><div id="hh">0</div><td>'
+hrs+' : <td><div id="mm">0</div><td>'
+min+' : <td><div id="ss">0</div><td>'
+sec+' <td>'
+day+'</td></td></td></td></td></td></td></tr></table>';
if(sec>9){
document.getElementById('ss').style.display = "none";
}else if(sec==0){
document.getElementById('ss').style.display = "block";
}
if(min>9){
document.getElementById('mm').style.display = "none";
}else if(min==0){
document.getElementById('mm').style.display = "block";
}
if(hrs>9){
document.getElementById('hh').style.display = "none";
}else if(hrs==0){
document.getElementById('hh').style.display = "block";
}
},
1000);
}else{
alert("Check time inputs...!");
}
}
//Set Hour, Minutes, Seconds by JS / manually
var date = new Date();
var hst = date.getHours();
var mst = date.getMinutes();
var sst = date.getSeconds();
timer(hst,mst,sst);
Since your "update every second" of the real clock competes with other computer tasks, the delay before the next real clock tic will be less than 1000 ms very often. So, better use setTimeout instead of setInterval. In fact, we just need to twist a little bit the end of the denied 姚先进's solution here arround, resulting in:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk, 1000 - a % 1000);
}
This is my clock solution since 2007.
here we go
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
setInterval(() => {
var a = new Date();
document.getElementById("disp").innerHTML = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
},1000);
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>
ok i have a cool digital clock and javascript but i cant get it to update every minute, help?
<html>
<head>
<style type="text/css">
#font-face {
font-family: Digital;
src: url('digital.ttf');
}
html {
font-family: "Digital";
font-size: 130px;
}
#clock {
color: red;
}
</style>
<script type="text/javascript" language="JavaScript">
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (minute < 10) { minute = "0" + minute; }
var timeString = hour +
':' +
minute
return timeString;
}
</script>
</head>
<body bgcolor="#000;" onload="init();">
<p id="clock" align="center">hi</p>
<script type="text/javascript" language="JavaScript"><!--
var clockTime = getClockTime();
document.getElementById('clock').innerHTML = clockTime;
</script>
<script type=text/javascript>
function init()
{
getClockTime();
window.setInterval(getClockTime,30000);
}
</script>
</body>
</html>
You are better off to use consecutive setTimeout calls and calcualte the time to wait each time. setInterval is not guaranteed to run at exactly the time you specify, so the clock will slowly drift. Also, if the user doesn't start it exactly on a whole minute, the clock will update out of sync with the system clock.
A modified init function is below that will call the clock setting function about 5ms after the next whole minute each and every time.
function init()
{
var interval = (60 - (new Date()).getSeconds()) * 1000 + 5;
getClockTime();
setTimeout(init,interval);
}
<html>
<head>
<style type="text/css">
#font-face {
font-family: Digital;
src: url('digital.ttf');
}
html {
font-family: "Digital";
font-size: 130px;
}
#clock {
color: red;
}
</style>
<script type="text/javascript" language="JavaScript">
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (minute < 10) { minute = "0" + minute; }
var timeString = hour +
':' +
minute +
':' +
second
document.getElementById('clock').innerHTML = timeString;
}
</script>
</head>
<body bgcolor="#000;" onload="init();">
<p id="clock" align="center">hi</p>
<script type="text/javascript" language="JavaScript"><!--
var clockTime = getClockTime();
</script>
<script type=text/javascript>
function init()
{
getClockTime();
setInterval(getClockTime,1000);
}
</script>
</body>
</html>
This line does nothing as you never accept the return value :
return timeString;
Instead use that to set the value of your
document.getElementById("clock").innerHTML = timeString;
A nifty regex will do the trick. Do, however, understand that the functions setTimeout and setInterval are highly unreliable for correctly managing time.
$('#clock').ready(function(){
var updateClock = function(){
var time = (new Date()).toString().match(/ (\d\d:\d\d):\d\d/);
$('#clock').text(time[1]);
};
setInterval(function(){
updateClock();
},60000);
updateClock();
});
This is my solution for react with hooks.
import { useState, useEffect } from "react";
export default function useTime() {
const [time, setTime] = useState(new Date());
useEffect(() => {
function getTime() {
let interval = (60 - new Date().getSeconds()) * 1000 + 5;
setTime(new Date());
setTimeout(getTime, interval);
}
getTime();
}, []);
return time;
}
I see two issues:
You are updating the clock every 30 seconds (30000 milliseconds). Is that intentional?
getClockTime will be called on the interval. Put document.getElementById('clock').innerHTML = timeString; as the last line of your function, and you should be good to go.
Added meridiem and post meridiem, fixed bug with seconds not having a preceding zero while less than 10 to #Rob 's answer
<html>
<head>
<style type="text/css">
#font-face {
font-family: Digital;
src: url('digital.ttf');
}
html {
font-family: "Digital";
font-size: 130px;
}
#clock {
color: red;
}
</style>
<script type="text/javascript" language="JavaScript">
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var meridiem = "AM";
if (hour > 12) { hour = hour - 12; $meridiem = "PM" }
if (hour == 0) { hour = 12; }
if (minute < 10) { minute = "0" + minute; }
if (second < 10) { second = "0" + second; }
var timeString = hour +
':' +
minute +
':' +
second +
' ' +
meridiem
document.getElementById('clock').innerHTML = timeString;
}
</script>
</head>
<body bgcolor="#000;" onload="init();">
<p id="clock" align="center">hi</p>
<script type="text/javascript" language="JavaScript"><!--
var clockTime = getClockTime();
</script>
<script type=text/javascript>
function init()
{
getClockTime();
setInterval(getClockTime,1000);
}
</script>
</body>
</html>
setTimeout("location.reload(true);",timeoutPeriod)