2015-09-04 82 views
-1

以下是我正在处理的计时器脚本中的一个JavaScript setInterval函数。JavaScript setInterval每隔X几分钟发布一次AJAX?

它基本上每秒计算一次。我想要做的就是每2分钟通过AJAX请求将这段时间发布到服务器。

我只需要帮助确定何时达到每2分钟,以便我可以插入我的AJAX代码。

有人可以告诉我如何确定下面这段代码中的每个2分钟的时间间隔吗?

timer.interval = setInterval(tick = function() { 
    /* Don't do anything if the timer is paused */ 
    if (timer.paused) return; 

    /* Calculate the number of seconds from the startTime */ 
    var sec = M.max(M.round((Date.now() - startTime) * dir/1000), 0); 

    var val = { 
     S: sec,      /* Total number of seconds */ 
     s: sec % 60,    /* Seconds */ 
     M: M.floor(sec /= 60),  /* Total minutes */ 
     H: M.floor(sec /= 60),  /* Total hours */ 
     D: M.floor(sec /= 24)  /* Total days */ 
    }; 
    val.m = val.M % 60;    /* Minutes */ 
    val.h = val.H % 24;    /* Hours */ 
    val.d = val.D;     /* Days */ 

    /* Format the timer */ 
    val.text = (options.format || '%-H{:}%0m:%0s').replace(
     /%(-?)(0?)([dhms])(\s*)(?:\{(.+?)\})?/ig, 
     options.replacer || function (match, omit, zero, part, space, forms) { 
      /* The value of the selected part */ 
      var v = val[part]; 

      /* 
      * 'day'  -> [ 'day', 'day', 'day' ] 
      * 'day|days' -> [ 'day', 'days', 'days' ] 
      */ 
      (forms = (forms||'').split('|'))[2] = 
       forms[2] || (forms[1] = forms[1] || forms[0]); 

      /* 
      * Return the output text, or an empty string if the value is 
      * zero and isn't supposed to be shown 
      */ 
      return !v && omit ? '' : 
       /* 
       * Initialize the output text with the value (and optionally 
       * a leading zero) 
       */ 
       (v > 9 ? '' : zero) + v + space + 

       /* Add the appropriate form */ 
       forms[+(v != 1) + 
        (v != 1 && (v%10 < 2 || v%10 > 4) || 
         (v > 10 && v < 20))]; 
     }); 

    /* 
    * If we have an element, put the formatted text inside it 
    * (otherwise, set "timerElem" to this instance of tinyTimer, so that it gets 
    * passed to callbacks) 
    */ 
    timerElem ? $(timerElem).html(val.text) : timerElem = timer; 

    /* Invoke the onTick callback (if defined) */ 
    (options.onTick || doNothing).call(timerElem, timer.val = val); 


}, 1000); 
+0

您可以使用** Counter **。意味着计数呼叫,当它达到120时,则进行ajax呼叫。 –

+0

你不能使用'setInterval(function(){//传递timer.interval通过ajax},120000)'? –

+0

@MuhammadUsman我看到了,所以增加计数器,当它达到120使我的AJAX调用和重置计数器回到0,所以它将启动过程 – JasonDavis

回答

3

您可以添加计数器这将算你的电话,什么时候会达到120,然后拨打电话的AJAX发布数据。

var counter = 0 ; 
timer.interval = setInterval(tick = function() { 

    /// your stuff 
    counter++; 
    if(counter == 120) 
    { 
     /// make ajax call 
     /// then 
     counter = 0; 
    } 

}, 1000); 
相关问题