0

I have an object which contains some data about progression of a bar but it keeps stopping at 99% and won't continue, i believe its because client time is not going to be the same as server time accurately enough to do it. So i don't know how to solve it.

These 2 timers are created server side and sent to the client.

myOjb[i].end: 1374805587 //seconds since epoch for when 100% is made
myObj[i].strt: 1374805527 //seconds since epoch when it started

The function that is calculating the percentage :

function clocker() {
    var now = new Date().getTime() / 1000;
    for (var i in myObj) {
        if (myObj[i].end > now) {
            var remain = myObj[i].end - now;
            var per = (now - myObj[i].strt) / (myObj[i].end - myBuildings[i].strt) * 100;
            var per = fix_percentage(per); // stops > 100 and < 0 returns int if true

            myObj[i].percentage = Math.ceil(per);

            console.log(myObj[i].percentage); //reaches 99 max

            if (myObj[i].percentage > 99) {
                console.log('test'); //never occurs
                return false;
            }
            break;
        } else {
            continue;
        }
    }
    setTimeout(clocker, 1000);
}

function fix_percentage(per){
    if(per>100)per=100;
    if(per<0)per = 0;

    return Math.round(per);
}

How could i sync the two together so the timing is more accurate ?

4

1 回答 1

1

编辑:原始答案是基于一个错误的假设。我认为正在发生的事情基本上是您将百分比设置为 100 的块可能会被跳过。如果在一次迭代中, 的值per< 99.5 但 > 88.5,就会发生这种情况。在这种情况下,四舍五入per的值为 99。然后,一秒钟后,当再次调用该函数时,外部 if 块将不会进入,因为myObj[i].end > nowfalse。以下代码将确保如果时间到期并且myObj[i].percentage由于上述情况而 < 100,它将被设置为 100 并像另一个 if 块一样返回。

if (myObj[i].end > now) {
        var remain = myObj[i].end - now;
        var per = (now - myObj[i].strt) / (myObj[i].end - myBuildings[i].strt) * 100;
        var per = fix_percentage(per); // stops > 100 and < 0 returns int if true

        myObj[i].percentage = Math.ceil(per);

        console.log(myObj[i].percentage); //reaches 99 max

        if (myObj[i].percentage > 99) {
            console.log('test'); //never occurs
            return false;
        }
        break;
    } else if ( (now >= myObj[i].end) && (myObj[i].percentage < 100) ) {
        console.log('Time expired, but percentage not set to 100')
        myObj[i].percentage = 100;
        return false;
    } else {
        continue;
    }
于 2013-07-26T03:14:15.293 回答