实时功能

Live time function

本文关键字:功能 实时      更新时间:2023-09-26

我已经设置了我的Agotime函数。我只是想知道我应该使用什么方法来让我的时间更新。很多人会说Ajax,但这会是服务器繁重吗?我需要每 5 秒平稳更换一次。

另外我该怎么做?

 function Agotime($date)
    {
        if(empty($date)) {
            return "No date provided";
        }
        $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
        $lengths         = array("60","60","24","7","4.35","12","10");
        $now             = time();
        $unix_date       = strtotime($date);
           // check validity of date
        if(empty($unix_date)) {    
            return "Bad date";
        }
        // is it future date or past date
        if($now > $unix_date) {    
            $difference     = $now - $unix_date;
            $tense         = "ago";
        } else {
            $difference     = $unix_date - $now;
            $tense         = "from now";
        }
        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
            $difference /= $lengths[$j];
        }
        $difference = round($difference);
        if($difference != 1) {
            $periods[$j].= "s";
        }
        return "$difference $periods[$j] {$tense}";
    }

您可以通过以下两种方式之一实现它。

你可以按照你的建议使用AJAX,并查询你的PHP脚本多久以前。但是,这可能会对请求数量造成很大影响。

你也可以在 Javascript 中实现这个函数,只需在加载时将包含传递时间戳传递给脚本。这样,您就不必对服务器执行任何请求,并且可以保持时间更新。当然,这假设时间戳不会更改。

我个人会选择选项 #2,因为它在 Javascript 中很容易计算,并且避免了大量的网络流量。

最好的选择是传入递增的日期,使用 setTimeout 并每 5 秒触发一次

然后,如果您愿意,可以进行"检查"以确保服务器上的时间与您在浏览器中的时间匹配,请使用每X次更新的ajax调用来"重新同步"日期/时间