2011-08-01 181 views
1
var sec = 10 
var timer = setInterval(function() { 
$('#timer span').text(sec--);  
if (sec == -1) { 
    clearInterval(timer); 
} }, 1000); 

html 

<div id="timer"><span>10</span> seconds</div> 
<a href="#" id="recount">Recount</a> 

當我點擊重新計數時,我想要做的事情是重新計時10秒鐘?setInterval重新計算?

我怎麼可能做到這一點? 最好使用setInterval()setTimeout()

回答

2

分解出你的代碼的功能,所以你可以調用在啓動時或相同的代碼鏈接被點擊。你可以看到它在這裏工作:http://jsfiddle.net/jfriend00/x3S7j/。這甚至可以讓你在倒計時期間點擊鏈接,它將重新開始。

$("#recount").click(function() { 
    initCounter(10); 
}); 

var remainingTime; 
var runningInterval = null; 

function initCounter(duration) { 

    function stopCounter() { 
     if (runningInterval) { 
      clearInterval(runningInterval); 
      runningInterval = null; 
     } 
    } 

    stopCounter();        // stop previously running timer 
    remainingTime = duration;     // init duration 
    $('#timer span').text(remainingTime);  // set initial time remaining 
    runningInterval = setInterval(function() { // start new interval 
     $('#timer span').text(remainingTime--);  
     if (remainingTime < 0) { 
      stopCounter(); 
     } 
    }, 1000); 
} 


initCounter(10); 
+0

這是工作很棒!那個我想要做的事我得到了最後的答案,非常感謝你! – noviceRick

1

當您單擊各顯神通,你應該

sec = 10; 
clearInterval(timer); 
timer = setInterval(that_function, 1000); 

此外,還有setIntervalsetTimeout之間的差異。 setInterval調度每個毫秒需要調用的函數。 setTimeout調度函數在幾毫秒後調用一次。

+0

你有一點,但如何在頁面加載時運行that_function?然後這就是當我點擊recount時它會重新計算 – noviceRick

2

你可以只添加一個單擊處理程序,並分解出你的代碼在一個單獨的方法:

var sec = 10; 
var timer; 

function startCountdown() { 
    if (timer) clearInterval(timer); 
    sec = 10; 

    timer = setInterval(function() { 
     $('#timer span').text(sec--); 
     if (sec == -1) { 
      clearInterval(timer); 
     } 
    }, 1000); 
} 

$(function() { 
    startCountdown(); 
    $("#recount").click(startCountdown); 
}); 

Working JSFiddle

+0

謝謝,但它似乎不起作用10seonds計時器沒有運行,當我點擊重新計數它不會太 – noviceRick

+0

@Gerald:檢查jsfiddle鏈接 - 它的工作原理就好了 – BrokenGlass

+0

它與jfriend00一樣也很棒謝謝你們我真的讚揚你的回答:)我是js的新手 – noviceRick