2013-08-05 47 views
0

我有一個JS代碼的問題。Javascript Cookie - 倒數

我試圖從2點之間的隨機數開始倒計時(在本例中爲50 & 60),並以隨機間隔倒計時。如果用戶刷新,我希望倒數繼續從刷新前的最後一個地方開始。我設法得到如此接近,但現在(特別是在FF)我不斷得到(NaN)作爲輸出。

有人可以救我從砸我的筆記本電腦嗎? :)

感謝

<script> 
    var minSpaces = 50; //Minimum spaces to start with 
    var maxSpaces = 60; //Maximum spaces to start with 
    var maxDecTime = 6000; //Max time interval between decrements 
    var minDecTime = 300; //Min time interval between decrements 
    var redirectWhenDone = 0; //Redirect = 1 set to 0 for no redirect 
    var stopSpaces = 3; //Number it will stop at if not using redirect 
    var redirectLocation = 'http://www.google.com'; 

    if(document.cookie) { 
     maxSpaces = parseInt(document.cookie); 
     minSpaces = parseInt(Math.max(maxSpaces-5, 1)); 
    } 
    var spaces = Math.floor(Math.random()*(maxSpaces-minSpaces+1)+minSpaces); 
    function updateSpaces() { 
     spaces--; 
     document.cookie = spaces+'; expires=Thu, 2 Aug 2015 20:47:11 UTC; path=/'; 
     document.getElementById('spaces').innerHTML = 
      '<span style="color:orange;">('+spaces+')</span> orders left!'; 
     var intvl = Math.round(Math.random()*maxDecTime) + minDecTime; 
     if(spaces>stopSpaces){ 
      setTimeout(updateSpaces, intvl); 
     } 
     else {//No spaces left, redirect! 
      if(redirectWhenDone==1) { 
       window.top.location = redirectLocation; 
      } 
}} 
    window.onload=updateSpaces; 
</script> 

回答

0

我會用sessionStorage舉辦一些JSON和setTimeout

function randomInt(min, max) { 
    return min + Math.floor(Math.random() * (max - min + 1)); 
} 

function randomCountdown(current, interval) { 
    var minStart = 50, maxStart = 60, 
     minInterval = 300, maxInterval = 6000; 
    var json = JSON.parse(window.sessionStorage.getItem('randomCountdown') || '{}'); 
    current = current || json.current || randomInt(minStart, maxStart); 
    interval = interval || json.interval || randomInt(minInterval, maxInterval); 
    window.sessionStorage.setItem('randomCountdown', JSON.stringify({ 
     current: current, 
     interval: interval 
    })); 
    if (--current) { 
     console.log('countdown', current, interval); 
     // do whatever 
     window.setTimeout(
      function() {randomCountdown(current, interval)}, 
      interval 
     ); 
    } else { 
     console.log('done'); 
    } 
} 

randomCountdown(); // start 
+0

我很欣賞的答覆,但我有點困惑(和重笨) - 我是正確的假設上面的代碼需要放在標籤內?如果是的話,我嘗試過,沒有任何反應。再次感謝 –

+0

行'console.log'和'//做任何事情'都需要改變爲你想要的行動,''current''每次迭代減少'1'。這段代碼讓你可以看到它在控制檯中恢復倒計時的例子 –