0

我对一些 JS 代码有疑问。

我试图让倒计时从 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>
4

1 回答 1

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
于 2013-08-05T16:24:29.263 回答