2015-02-24 87 views
2

我有這countDown,每次我按下按鈕我想添加5多秒。setInterval countDown更新時間

當更新時間時,函數也會計算新值,但也是舊值。

有人可以解釋我爲什麼嗎?

http://jsfiddle.net/xqdj3uz8/1/

$('button').on('click', function() { 
    var newtime = parseInt(seconds + 5); 
    timer(newtime);  
}); 
+1

http://jsfiddle.net/xqdj3uz8/3/ – kuba 2015-02-24 09:23:19

回答

1

您可以通過使用全局變量來跟蹤的左秒爲單位嘗試。點擊按鈕將增加這個變量。

var timeLeft = 10; 

function timer() { 
    var i = setInterval(function() { 
     $('span').text(timeLeft); 
     timeLeft-- 
     if (timeLeft === 0) clearInterval(i) 
    }, 1000) 
} 

function addSeconds(n) { 
    timeLeft += n 
} 

timer() 

$('button').on('click', function() { 
    addSeconds(5) 
}); 

演示(1):http://jsfiddle.net/xqdj3uz8/21/

1

請使用

function timer(time) { 
    var interval = setInterval(countDown, 1000);  
    function countDown() { 
     time--; 
     $('span').text(time); 

     if(time === 0) { 
      clearInterval(interval); 
     } 

    }  



    $('button').on('click', function() { 

     time=parseInt(time + 5); 
     $('span').text(time); 

    }); 
} 

var seconds = 5; 
timer(seconds); 
1

嘗試這個

Working JSFIDDLE

var gblTime=0; 
function timer(time) { 
    var interval = setInterval(countDown, 1000); 
    gblTime = time; 
    function countDown() { 
     gblTime--; 
     $('span').text(gblTime); 

     if(gblTime <= 0) { 
      clearInterval(interval); 
     } 

    }   
} 

var seconds = 5; 
timer(seconds); 

$('button').on('click', function() { 

    gblTime = parseInt(gblTime +1+ 5); 
    //timer(newtime);  
}); 
+0

@Marius - 請參閱上面的JSFIDDLE鏈接 - 它正在工作 – prog1011 2015-02-24 09:36:15

-1

您要添加新的區間是獨立形式對方,嘗試:

var time = 5; 
var seconds = 5; 

function timer() { 
    var interval = setInterval(countDown, 1000);  
    function countDown() { 

    $('span').text(time); 
    if(time === 0) { 
     clearInterval(interval); 
    } 
    time--;   
    }   
} 

timer(); 

$('button').on('click', function() { 
    if(time==0){ 
    timer(); 
    } 
    time += seconds; 
});