2014-01-15 40 views
0

我在js中創建了一個非常簡單的倒數計時器,每個時間元素都計算出來。它是有效的,唯一的問題是每秒都會有計算量出現滯後現象。任何想法如何使這更高效?低效的JavaScript倒數計時器

JS:

var count = 55010; //needs to be in seconds 
var counter = setInterval(timer, 1000); //1000 will run it every 1 second 
function timer(){ 
    count = count-1; 
    if (count <= -1){ 
    clearInterval(counter); 
    return; 
    } 
    document.getElementById("hour10").innerHTML=Math.floor(((count/86400)%1)*2.4); 
    document.getElementById("hour1").innerHTML=Math.floor(((count/86400)%1)*24)-(Math.floor(((count/86400)%1)*2.4))*10; 
    document.getElementById("min10").innerHTML=Math.floor(((count/3600)%1)*6); 
    document.getElementById("min1").innerHTML = Math.floor(((count/3600)%1)*60)-(Math.floor(((count/3600)%1)*6))*10; 
    document.getElementById("sec10").innerHTML = Math.floor(((count/60)%1)*6); 
    document.getElementById("sec1").innerHTML = Math.floor(((count/60)%1)*60)-(Math.floor(((count/60)%1)*6))*10; 
} 

HTML:

<span id="hour10">0</span> 
<span id="hour1">0</span> : 
<span id="min10">0</span> 
<span id="min1">0</span> : 
<span id="sec10">0</span> 
<span id="sec1">0</span> 

我已經創建了以這種方式計時器的原因是因爲我想把每個元素爲一個div容器,像這樣:

enter image description here

在此先感謝!

+3

滯後是從你的瀏覽器不也用的innerText對於如何準確記錄時間非常謹慎。你的計算幾乎沒有時間。 – Pointy

+0

滯後的原因不是使用低效計算,而是漂移'setInterval'。只需將其更改爲使用[準確時間](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)。 – Bergi

+0

[javascript setInterval - 倒計時滯後]的可能重複(http://stackoverflow.com/questions/14186771/javascript-setinterval-countdown-lagging) – Cilan

回答

1

一個辦法,使之更有效率僅是通過搜索DOM的一次,以保持對元素的參考,如果你不使用任何標記

var count = 55010; //needs to be in seconds 
var counter = setInterval(timer, 1000); //1000 will run it every 1 second 
var elHour10 = document.getElementById("hour10"); 
var elHour1 = document.getElementById("hour1"); 
var elMin1 = document.getElementById("min10"); 
var elSec10 = document.getElementById("sec10"); 
var elSec1 = document.getElementById("sec1"); 

function timer(){ 
    count = count-1; 
    if (count <= -1){ 
    clearInterval(counter); 

    return; 
    } 
    elHour10.innerText=Math.floor(((count/86400)%1)*2.4); 
    elHour1.innerText=Math.floor(((count/86400)%1)*24)-(Math.floor(((count/86400)%1)*2.4))*10; 
    elMin10.innerText=Math.floor(((count/3600)%1)*6); 
    elMin1.innerText = Math.floor(((count/3600)%1)*60)-(Math.floor(((count/3600)%1)*6))*10; 
    elSec10.innerText = Math.floor(((count/60)%1)*6); 
    elSec1.innerText = Math.floor(((count/60)%1)*60)-(Math.floor(((count/60)%1)*6))*10; 
}