使用setInterval()每2秒获取一个新时间。新时间比现在提前30秒

时间:2015-10-12 18:26:36

标签: javascript jquery date setinterval

首先我将div.test的文本设置为将来一分钟的字符串。然后每2秒我希望该时间每30秒增加一次。现在时间每2秒增加2秒。 (我认为在第一个Interval是例外,因为只增加30秒。)我希望文本的秒部分每2秒间隔增加30秒。



function getStringFormat(d) {
  function getFullDay(d) {
    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    return weekday[d.getDay()];
  }

  function getFullMonth(d) {
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    return months[d.getMonth()]
  }
  return getFullDay(d) + ", " + getFullMonth(d) + " " + d.getDate() + ", " + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()
}

//first deadline
function getNewFutureTime(t) {
  return getStringFormat(new Date(new Date().getTime() + t * 1000))
    // oned
}
$(".test").html(getNewFutureTime(60));
setInterval(function() {
  $(".test").html(getNewFutureTime(30));
}, 2 * 1000)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

不是每次运行getNewFutureTime时都创建一个新日期,而是应该在代码开头抓取当前时间,然后每2秒增加一次。

var futureDate = new Date();

        function getStringFormat(d){
            function getFullDay(d){
                var weekday = ["Sunday", "Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
                return weekday[d.getDay()];
            }

            function getFullMonth(d){
                var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                return months[d.getMonth()]
            }
            return getFullDay(d) +", " + getFullMonth(d) +" "+ d.getDate() + ", " + d.getFullYear() + " " +  d.getHours()+":"+ d.getMinutes() +":" + d.getSeconds()
        }

        //first deadline
        function getNewFutureTime(t){
            futureDate.setTime(futureDate.getTime() + t * 1000);
            return getStringFormat(futureDate)
            // oned
        }
        $(".test").html(getNewFutureTime(60));
        setInterval(function(){
            $(".test").html(getNewFutureTime(30));
        }, 2 * 1000)

FIDDLE