针对不同元素多次调用同一函数

时间:2019-05-13 01:08:04

标签: javascript jquery nested-function uptime

我正在尝试创建计时器,并尝试为具有不同ID的不同元素调用函数。但是第二个呼叫会覆盖第一个呼叫,并且它需要2秒而不是1秒。

部分JavaScript代码

$(function() {
  startTimer('#uptime',195791);
  startTimer('#uptime2',957291);
});

function startTimer(wrapper, startDate) {
   // Calculate time until launch date
      targetDate = startDate;   
      timeToLaunch();
      timerWrapperObj = wrapper;
      // Transition the current countdown from 0 
      numberTransition(timerWrapperObj+' .ut-days .count', days, 1000, 'easeOutQuad');
      numberTransition(timerWrapperObj+' .ut-hours', hrs, 1000, 'easeOutQuad');
      numberTransition(timerWrapperObj+' .ut-minutes', min, 1000, 'easeOutQuad');
      numberTransition(timerWrapperObj+' .ut-seconds', sec, 1000, 'easeOutQuad');
      // Begin Countdown
      setTimeout(countDownTimer(wrapper),1001);

}

function countDownTimer(wrapper){ 

    // Figure out the time to launch
    timeToLaunch();
    if(days < 10) {days = '0'+days}
    if(hrs < 10) {hrs = '0'+hrs}
    if(min < 10) {min = '0'+min}
    if(sec < 10) {sec = '0'+sec}
    // Write to countdown component
    $( wrapper+" .ut-days .count" ).text(days);
    $( wrapper+" .ut-hours" ).text(hrs);
    $( wrapper+" .ut-minutes" ).text(min);
    $( wrapper+" .ut-seconds" ).text(sec);
    console.log(wrapper);
    // Repeat the check every second
    setTimeout(countDownTimer,1000,wrapper);
}

HTML

<div class="uptime-timer" id="uptime">
    <span class="ut-days" id="ut-days"><span class="count"></span></span>
    <span class="ut-hours" id="ut-hours"></span>:
    <span class="ut-minutes" id="ut-minutes"></span>:
    <span class="ut-seconds" id="ut-seconds"></span>
</div>

<div class="uptime-timer" id="uptime2">
    <span class="ut-days" id="ut-days2"><span class="count"></span></span>
    <span class="ut-hours" id="ut-hours2"></span>:
    <span class="ut-minutes" id="ut-minutes2"></span>:
    <span class="ut-seconds" id="ut-seconds2"></span>
</div>

将完整代码添加到codepen

0 个答案:

没有答案