Javascript - Tạo đồng hồ và hiển thị thời gian theo từng giây

Viết chương trình JavaScript để tạo Đồng hồ.

Lưu ý: Sau mỗi giây hiển thị kết quả.

Mã nguồn:

<!DOCTYPE html>
  <html>
  <head>
  <meta charset="utf-8">
  <title>Create a clock and display the time in each second </title>
	  <script>
		  function my_Clock() 
		  {
		  this.cur_date = new Date();
		  this.hours = this.cur_date.getHours();
		  this.minutes = this.cur_date.getMinutes();
		  this.seconds = this.cur_date.getSeconds();
		  }
		my_Clock.prototype.run = function ()
		  {
		  setInterval(this.update.bind(this), 1000);
		  };
		my_Clock.prototype.update = function () 
		  {
		  this.updateTime(1);
		  document.write(this.hours + ":" + this.minutes + ":" + this.seconds+"<br/>");
		  };
		my_Clock.prototype.updateTime = function (secs) 
		  {
		  this.seconds+= secs;
		 if (this.seconds >= 60)
		  {
		  this.minutes++;
		  this.seconds= 0;
		  }
		 if (this.minutes >= 60)
		  {
		  this.hours++;
		  this.minutes=0;
		  }
		if (this.hours >= 24)
		  {
		  this.hours = 0;
		  }
		};
		var clock = new my_Clock();
		  clock.run();
	  </script>
  </head>
  <body>
</body>
  </html>
  

Xem ví dụ

Lưu đồ thuật toán:

Flowchart: JavaScript - Create a clock and display the time in each second.


Chatbot Tư vấn Lộ trình CNTT 🤖
Chào bạn! Tôi có thể tư vấn về các lộ trình học CNTT dựa trên roadmap.w3typing.com. Hãy chọn một từ khóa dưới đây hoặc gõ câu hỏi của bạn (ví dụ: "Frontend", "Backend", "Python", "DevOps").