dongzhang1839 2013-04-28 04:47
浏览 93
已采纳

拍卖网站的PHP / jquery倒计时器

I am looking for a countdown timer for an auction site that won't change when a user changes their local computer clock.

I have used Keith Woods with the server sync but wondering if anyone has had any experience with any others as even that script changes when a user changes their clock.

I would like something like eBay has.

Cheers

  • 写回答

1条回答 默认 最新

  • duanpan7011 2013-04-28 07:19
    关注

    Depending how accurate (milliseconds etc) you want this to be, a simple setInterval (Doc) on a your count down function can get somewhat accurate results and couldn't be changed by someone changing their clock.

    As this method depends on the javascript executing, it could be delayed by the page load speed or other things causing it to become out of sync. However if you had it do an AJAX call to the webserver every minute or so, it could re-sync the time on the client to make sure no significant delays have occurred.

    So simply:

    var currentTime = [6,50,20]; //[Hours,Minutes,Seconds]
    var intervalId;
    function updateTime()
    {
        currentTime[2]--;
    
        if (currentTime[0] == 0 && currentTime[1] == 0 && currentTime[2] == 0)
        {
            clearInterval(intervalId);
    
            //do your processing of countdown end here
        }
    
        if (currentTime[2] == -1)
        {
            currentTime[2] = 59;
            currentTime[1]--;
        }
        if (currentTime[1] == -1)
        {
            currentTime[1] = 59;
            if (currentTime[0] > 1)
            {
                currentTime[0]--;
            }
        }
    
        //do your processing of current time here (ie. display on screen)
    }
    
    //Use this function as the callback to an AJAX request to the server
    //This will sync the time correctly
    function ajaxCurrentTime(AJAXResponse)
    {
        //For this example, we will say the AJAXResponse is a JSON string
        currentTime = JSON.parse(AJAXResponse);
    }
    
    intervalId = setInterval(updateTime,1000);
    

    I will be the first to admit it isn't the perfect solution because of potential inaccuracies of a few seconds at the most however it doesn't touch the date/time of the client machine so couldn't be affected by them changing the time.

    The code I provided doesn't include the part that actually does the AJAX communication, just the callback for it. It is just an example of one way this could be implemented, there is no real error checking and may have other issues that I have not noticed, use it as a guide.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?