Making a live clock in javascript

2019-05-10 13:32发布

The clock kinda works. But instead of replacing the current time of day it prints a new time of day every second. I understand why it do it but I don't know how to fix it. I would appreciate if you could give me some tips without saying the answer straight out. Thank you. Here is my code:

function time(){
    var d = new Date();
    var s = d.getSeconds();
    var m = d.getMinutes();
    var h = d.getHours();
    document.write(h + ":" + m + ":" + s);
}

setInterval(time,1000);

6条回答
Lonely孤独者°
2楼-- · 2019-05-10 13:45

anyone wanting to know how to code a digital clock with alarm? Here is my codepen http://codepen.io/abhilashn/pen/ZLgXbW

function AmazeTime(almbtnobj) {
	this.date,this.day,this.dt,this.month, this.year,this.hour,this.minute,this.second = null;
	this.almHour, this.almMinute, almMeridiem = null;
	this.meridiem = "AM";
	this.almBtn = almbtnobj;
	this.almBtn = this.setAlarm;
}

AmazeTime.prototype.initializeTime = function() {
	this.dt = new Date();
	this.day = this.getDayInWords(this.dt.getDay());
	this.date = this.dt.getDate();
	this.month = this.getMonthInShort(this.dt.getMonth());
	this.year = this.dt.getFullYear();
	this.hour = this.setHour(this.dt.getHours());
	this.minute = this.doubleDigit(this.dt.getMinutes());
	this.second = this.doubleDigit(this.dt.getSeconds());
	this.meridiem = this.setMeridiem(this.dt.getHours());
}

AmazeTime.prototype.setHour = function(hr) {	
	if(hr > 12) {
		hr = hr - 12;
	}
	if(hr === 0) {
		hr = 12;
	}
	return this.doubleDigit(hr);
}

AmazeTime.prototype.doubleDigit = function(val) {
	if(val < 10) {
		val = "0" + val;
	}
	return val;
}
AmazeTime.prototype.setMeridiem = function(hr) {
	if(hr > 12) {
		hr = hr - 12;
		return "PM";
	} else {
		return "AM";
	}
}

AmazeTime.prototype.getMonthInShort = function(value) {
	switch(value) {
		case 0:
			return "Jan";
			break;
		case 1:
			return "Feb";
			break;
		case 2:
			return "Mar";
			break;
		case 3:
			return "Apr";
			break;
		case 4:
			return "May";
			break;
		case 5:
			return "Jun";
			break;
		case 6:
			return "Jul";
			break;
		case 7:
			return "Aug";
			break;
		case 8:
			return "Sep";
			break;
		case 9:
			return "Oct";
			break;
		case 10:
			return "Nov";
			break;
		case 11:
			return "Dec";
			break;		}
}

AmazeTime.prototype.getDayInWords = function(value) {
	switch(value) {
			case 0:
				return "Sunday";
				break;
			case 1:
				return "Monday";
				break;
			case 2:
				return "Tuesday";
				break;
			case 3:
				return "Wednesday";
				break;
			case 4:
				return "Thursday";
				break;
			case 5:
				return "Friday";
				break;
			case 6:
				return "Saturday";
				break;
	}	 	
}

AmazeTime.prototype.setClock = function() {
	var clockDiv = document.getElementById("clock");
	var dayDiv = document.getElementById("day");
	var dateDiv = document.getElementById("date");
	var self = this;
	dayDiv.innerText = this.day;
	dateDiv.innerText = this.date + " " + this.month + " " + this.year;
	clockDiv.innerHTML = "<span id='currentHr'>" + this.hour + "</span>:<span id='currentMin'>" + this.minute + "</span>:" + this.second + " <span id='meridiem'>" + this.meridiem + "</span>";
}

AmazeTime.prototype.setAlarm = function() {
	this.almHour = this.doubleDigit(document.getElementById('almHour').value);
	this.almMinute = this.doubleDigit(document.getElementById('almMin').value);
	if(document.getElementById("am").checked == true) {
		this.almMeridiem = "AM";
	} else  {
		this.almMeridiem = "PM";
	}
}
AmazeTime.prototype.checkAlarm = function() {
	var audio = new Audio('http://abhilash.site44.com/images/codepen/audio/audio.mp3');
	if(this.hour == this.almHour && this.minute == this.almMinute && this.almMeridiem == this.meridiem) {
		audio.play();
		if(this.minute > this.almMinute) {
			audio.pause();
		}
	} 
}

var mytime = null;
mytime = new AmazeTime(document.getElementById("savebtn"));
window.addEventListener('load', function() { 
	function runTime() {
	mytime.initializeTime();
	mytime.setClock();
	mytime.checkAlarm();
	}
setInterval(runTime, 1000);	
}	, false);	

function saveAlarm() {		
	mytime.setAlarm();
	$('#myModal').modal('hide');
}
 
 
document.getElementById("savebtn").addEventListener("click", saveAlarm , false);
			
body { background:#A3ABF2; font-family:Arial; text-align:center; }
.day { font-size:64px;  }
.date { font-size:33px; }
.clock { font-size:44px; }
.clock-content { margin-top:35vh; color:#FFF;  }
.alarm-icon { font-size:34px; cursor:pointer; position:absolute; top:15px; right:15px; color:#FFF; }
.setalmlbl { padding-right:20px; }
.setalmtxtbox { margin-right:10px; width:60px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i id="alarmbtn" data-toggle="modal" data-target="#myModal" class="fa fa-bell alarm-icon"></i>
		<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"> Set Alarm</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
	  <form>
      <div class="modal-body">
		
			<div class="form-inline">
			  <label for="hours" class="setalmlbl" >Hours  </label>
			  
				<select class="form-control setalmtxtbox" name="almHour" id="almHour">
				<script>
					for(var h = 1; h <= 12; h ++) {
				  document.write("<option value="+ h +">" + h + "</option>");
				  }
				</script>
				</select>
				
			 <label for="minutes" class="setalmlbl"> Minutes  </label>
				<select class="form-control setalmtxtbox" name="almMin" id="almMin">
				<script>
					for(var m = 1; m <= 60; m++) {
				  document.write("<option value="+ m +">" + m + "</option>");
				  }
				</script>
				</select>
			 <div class="form-check">
			  <label class="form-check-label">
				<input class="form-check-input" type="radio" name="meridiem" id="am" value="am" checked>
				 A.M.
			  </label>
			</div> 
			<div class="form-check">
			  <label class="form-check-label">
				<input class="form-check-input" type="radio" name="meridiem" id="pm" value="pm">
				P.M.
			  </label>
			</div> 
			 </form>
			
			
			
			</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" id="savebtn" class="btn btn-primary">Save</button>
      </div>
	 
    </div>
  </div>
</div>


		
		<div class="container-fluid">
			
			<div class="clock-content">
				<div class="day" id="day"></div>
				<div class="date" id="date"></div>
				<div class="clock" id="clock"></div>
			</div>
		</div>

查看更多
可以哭但决不认输i
3楼-- · 2019-05-10 13:55

What do you mean by "new time of day"? But in order to replace new time, you can create a div contain the time, and every time you call time(), set that div.innerHTML = "", like below

HTML:

<div id="curr_time"></div>

JS:

var div = document.getElementById('curr_time'); 
function time() {
  div.innerHTML = "";
  var d = new Date();
  var s = d.getSeconds();
  var m = d.getMinutes();
  var h = d.getHours();
  div.innerHTML = h + ":" + m + ":" + s;
}

setInterval(time, 1000);
查看更多
太酷不给撩
4楼-- · 2019-05-10 13:59

you can look at this simple javascript clock here in app.js for a live clock in the browser https://github.com/danielrussellLA/simpleClock

var clock = document.getElementById('clock');

setInterval(function(){
  clock.innerHTML = getCurrentTime();
}, 1);

function getCurrentTime() {
  var currentDate = new Date();
  var hours = currentDate.getHours() > 12 ? currentDate.getHours() - 12 : currentDate.getHours();
  hours === 0 ? hours = 12 : hours = hours;
  var minutes = currentDate.getMinutes();
  var seconds = currentDate.getSeconds() < 10 ? '0' + currentDate.getSeconds() : currentDate.getSeconds();
  var currentTime = hours + ':' + minutes + ':' + seconds;
  return currentTime;
}
查看更多
聊天终结者
5楼-- · 2019-05-10 14:00

Please follow this link https://codepen.io/uniqname/pen/eIApt you will get your desire clock or try this code

<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
</script>
</head>

<body onload="startTime()">

<div id="txt"></div>

</body>
</html>
查看更多
仙女界的扛把子
6楼-- · 2019-05-10 14:02

A working demo, follow the link

http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock

Updated you are using document.write which appends the current time each time (and that's what your problem was if I am not wrong). So for replacing previous time with new time - 1. you have to open document with replace mode (as shown in code below) 2. you write the current time 3. then you close the document.

function time(){
    var d = new Date();
    var s = d.getSeconds();
    var m = d.getMinutes();
    var h = d.getHours();
    document.open("text/html", "replace");
    document.write(h + ":" + m + ":" + s);
    document.close();
}

setInterval(time,1000);
查看更多
Animai°情兽
7楼-- · 2019-05-10 14:02

Add a span element and update its text content.

var span = document.getElementById('span');

function time() {
  var d = new Date();
  var s = d.getSeconds();
  var m = d.getMinutes();
  var h = d.getHours();
  span.textContent = h + ":" + m + ":" + s;
}

setInterval(time, 1000);
<span id="span"></span>

查看更多
登录 后发表回答