Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

javascript - 如何根据服务器时间设置JavaScript倒数计时器?(How make JavaScript countdown timer based on server time?)

I have to make a timer that counts down to a specific time.

(我必须制作一个倒计时到特定时间的计时器。)

I have already done something like this, but my timer counts down the time based on the client's time and it can be easily hacked.

(我已经做过类似的事情,但是我的计时器根据客户端的时间倒计时,因此很容易被黑客入侵。)

I know I have to do an AJAX query, but I don't know how to integrate it with my code.

(我知道我必须进行AJAX查询,但是我不知道如何将其与代码集成。)

I know the question is simple, I'm just learning.

(我知道问题很简单,我只是在学习。)

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2020 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("clock").innerHTML = "  " + hours + ":"
  + minutes + ":" + seconds;

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("clock").innerHTML = " Koniec czasu!";
  }
}, 1000);

and AJAX:

(和AJAX:)

$(function () {
  $.ajax({
    type: 'GET',
    cache: false,
    url: location.href,
    complete: function (req, textStatus) {
      var dateString = req.getResponseHeader('Date');
      if (dateString.indexOf('GMT') === -1) {
        dateString += ' GMT';
      }
      var date = new Date(dateString);
      $('#serverTime').text(date);
    }
  });
  var localDate = new Date();
  $('#localTime').text(localDate);
});

Can you help me?

(你能帮助我吗?)

  ask by Anarhak translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...