Javascript倒计时以获取当前运行的间隔时间

你好戴夫

我有使用 Javascript/jQuery 的倒计时功能。

function countdownto(target, time, callback) {
    var finish = new Date(time);
    var s = 1000,
        m = s * 60,
        h = m * 60,
        d = h * 24;

    (function timer() {
        var now = new Date();
        var dist = finish - now;

        var days = Math.floor(dist / d),
            hours = Math.floor((dist % d) / h),
            minutes = Math.floor((dist % h) / m),
            seconds = Math.floor((dist % m) / s);

        var timestring = days + 'days ' + hours + 'hrs ' + minutes + 'mins ' + seconds + 'seconds ';
        target.html(timestring)
        
        if (dist > 0) {
            setTimeout(timer, 1000);
        } else {
            callback()
        }
        
    })()

}

// 10 seconds into the future
var time = "08/02/2021 17:05:00";
var time2 = "08/02/2021 17:33:00";

// countdown function call
countdownto($('#countdown'), time, function(){
   console.log('tadaaa')
   
   countdownto($('#countdown2'), time2, function(){
     console.log('tadaaa')
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="countdown"></div>

<div id="countdown2"></div>

现在我需要在那里添加函数 interval second 来获取当前的间隔时间。

我的问题是:如何在此函数中获取间隔时间:

countdownto($('#countdown'), time, function(){
   console.log('tadaaa')

   alert(time); // <-- how to get interval time? Alert not appear, as I know here when the countdown finish.
   
   countdownto($('#countdown2'), time2, function(){
     console.log('tadaaa')
  })
})
沙德里奇

从技术上讲,您已经将时间作为全局time变量中的字符串如果你想把它传递给回调,你必须在调用回调的地方传递它:

function countdownto(target, time, callback) {
    var finish = new Date(time);
    var s = 1000,
        m = s * 60,
        h = m * 60,
        d = h * 24;

    (function timer() {
        var now = new Date();
        var dist = finish - now;

        var days = Math.floor(dist / d),
            hours = Math.floor((dist % d) / h),
            minutes = Math.floor((dist % h) / m),
            seconds = Math.floor((dist % m) / s);

        var timestring = days + 'days ' + hours + 'hrs ' + minutes + 'mins ' + seconds + 'seconds ';
        target.html(timestring)
        
        if (dist > 0) {
            setTimeout(timer, 1000);
        } else {
            callback(finish)
        }
        
    })()

}

// 10 seconds into the future
var time = "08/02/2021 17:05:00";
var time2 = "08/02/2021 17:33:00";

// countdown function call
countdownto($('#countdown'), time, function(time){
    console.log('tadaaa')

    alert(time); // <-- how to get interval time? Alert not appear, as I know here when the countdown finish.
   
    countdownto($('#countdown2'), time2, function(){
      console.log('tadaaa')
   })
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="countdown"></div>

<div id="countdown2"></div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章