2017-09-27 83 views
0

嗨,大家好我有问题,我的定时器,一个计时器工作正常,但是当我把它转换成多个计时器,计时器不工作有人可以帮我请谢谢改变单一到多元倒计时器使用JavaScript

我添加了一个正在工作的计时器片段 在此先感谢! :)

P.S我不能在这部分使用Jquery所以它是相当具有挑战性的。

// value came here $time_end = sprintf('%013.0f', microtime(true)*1000 + 27000000); 30 minuts timer 
 
var countDownDate = "1506509439553"; 
 

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

 
    // Get todays date and time 
 
    var now = new Date().getTime(); 
 

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

 
    // Time calculations for days, hours, minutes and seconds 
 
    var days = Math.floor(distance/(1000 * 60 * 60 * 24)); 
 
    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); 
 

 
    // Output the result in an element with id="demo" 
 
    document.getElementById("timer_1").innerHTML = minutes + ":" + seconds + ""; 
 
    //id is dynamic timer_<?php echo get_the_ID();?> 
 

 
    // If the count down is over, write some text 
 
    if (distance <= 0) { 
 
    clearInterval(x); 
 
    document.getElementById("timer_1").style.display = "none"; 
 
    } 
 
}, 1000);
<div id="timer_1"></div>

+0

使用一些倒闭? – evolutionxbox

回答

1

简单包装现有的代码放到一个方法,和元素的id传递给它。

演示

startTimer("timer_1"); 
 
startTimer("timer_2"); 
 
startTimer("timer_3"); 
 

 
function startTimer(elementId) { 
 
    // value came here $time_end = sprintf('%013.0f', microtime(true)*1000 + 27000000); 30 minuts timer 
 
    var countDownDate = "1506509439553"; 
 

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

 
    // Get todays date and time 
 
    var now = new Date().getTime(); 
 

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

 
    // Time calculations for days, hours, minutes and seconds 
 
    var days = Math.floor(distance/(1000 * 60 * 60 * 24)); 
 
    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); 
 

 
    // Output the result in an element with id="demo" 
 
    document.getElementById(elementId).innerHTML = minutes + ":" + seconds + ""; 
 
    //id is dynamic timer_<?php echo get_the_ID();?> 
 

 
    // If the count down is over, write some text 
 
    if (distance <= 0) { 
 
     clearInterval(x); 
 
     document.getElementById(elementId).style.display = "none"; 
 
    } 
 
    }, 1000); 
 
}
<div id="timer_1"></div> 
 
<div id="timer_2"></div> 
 
<div id="timer_3"></div>

+0

我认为把'countDownDate'作为参数也是一个很好的做法:) – Bartheleway

+0

哦,男孩非常感谢你,我花了很多时间在这工作谢谢@ gurvinder372 –

+0

@Bartheleway是的,我认为这个代码可以重构/旨在提高其可读性。 – gurvinder372