這裏有一個辦法,更符合JS設計(爲那些誰還不知道函數式語言)的方式調整。而不是依靠一個全局變量,使用閉包:
$("#knap").click(function start()//named callback to bind && unbind:
{
$(this).unbind('click');//no need to start when started
$("#reset").unbind('click').click((function(timer)
{//timer is in scope thanks to closure
return function()
{//resets timer
clearInterval(timer);
timer = null;
$('#knap').click(start);//bind the start again
//alternatively, you could change the start button to a reset button on click and vice versa
}
})(setInterval((function(sec)
{
return function()
{
$('#timer').text(sec--);
if (sec === -1)
{
$('#reset').click();//stops interval
$('#reset').unbind('click');//no more need for the event
alert('done');
}//here's the interval counter: 15, passed as argument to closure
})(15),1000)));//set interval returns timer id, passed as argument to closure
});
現在,我承認這是相當混亂(和未經測試),但這種方式存在重置事件僅當它是必要的,你不使用任何全局變量。但最重要的,這就是JS的強大之處在於:作爲第一類對象,將它們作爲參數和返回值...只是去功能瘋狂:)
我已經成立了一個工作Fiddle,太
-1醜陋的解決方案與全局變量... – Christoph 2012-08-02 15:51:54
我會接受你的答案。 – 2012-08-02 15:51:59
一流的代碼。謝謝。 – Kavin 2014-11-15 17:38:25