[英]Increment + auto-update variable value in JS
我是JS和PHP的初學者,所以請原諒我的無知並忍受我:)
我正在嘗試在我的網站上實施一個實時計數器。 此計數器應顯示到目前為止翻譯的單詞數量,我希望此數字更新為“實時”以反映翻譯單詞的數量(根據我的年平均值)。
為簡化起見,我設置了一個變量$ wordsPerYear,其平均每年翻譯一次,比如1000。 我還將開始日期設置為10年前(2004年),以便返回大約10,000。
所以這是我的代碼到目前為止:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Live Word Count</title>
<style type="text/css">
.count {
width: 100%;
margin: 0 auto;
padding-top: 10%;
text-align: center;
}
</style>
<?php
$now = time();
$start = mktime(0, 0, 0, 1, 01, 2004);
$wordsPerYear = 1000;
$totalDays = (($now - $start) / 86400); // number of a seconds in a day
$count = $totalDays / 365 * $wordsPerYear;
$count = round($count);
?>
<script type="text/javascript">
var totalWords = <?php print($count); ?>;
function updateCounter() {
totalWords = totalWords + 1; // need to do something here to update to the real word count instead of incrementing by 1 each second
document.getElementById("carb").innerHTML=totalWords; }
</script>
</head>
<body onload="setInterval('updateCounter()', 1000);">
<div class="count">
<span id="carb">
Loading Word Count...
</span>
</div>
</body>
</html>
我只需要能夠使用setInterval('updateCounter()',1000)使用翻譯的單詞的真實值而不是“假”實時增量使這個數字更新為“實時”。
所以,是的,我真的只需更新該功能,將該字數統計值更新為當前時間與開始日期的比率。
誰能幫我實現這個目標? 我確信這是一件非常簡單的事情,但是我絞盡腦汁無濟於事。 如果需要澄清來解釋我想做什么,請告訴我!
提前致謝
因為你實際上並沒有從服務器獲取任何值,所以不需要同時使用PHP和Javascript - 它們都是在真空中計算的。
從根本上說,這是一個數學問題。 Javascript計算日期的差異(以毫秒為單位),因此您首先需要知道每翻譯一毫秒的單詞數:每年/每年的單詞/每天的毫秒數。 我使用31556900作為每年測試的單詞值,因為這是一年中的秒數。
接下來,您必須將該總數應用於當前日期 - 開始日期,並將其設置為您的起始總日期。
最后,創建一個區間函數,將單詞數添加到總數中。
這應該這樣做:
;(function() {
// Constants
var wpm = (31556900 / 365) / 86400000 // Words per year / days per year / milliseconds per day
, start = new Date('January 1, 2004');
var now = new Date()
, total = Math.round((now - start) * wpm);
var dom = {
counter: document.getElementById('counter')
};
dom.counter.textContent = total;
setInterval(function() {
total += Math.round((new Date() - now) * wpm)
dom.counter.textContent = total;
now = new Date();
}, 1000)
}())
你可以嘗試這個,我只是在javascript中翻譯你的PHP代碼,並根據服務器時間計算你的“totalWords”。
<script>
var getServerTime = (function () {
var baseTime = <?php echo time() * 1000; /* convert to milliseconds */ ?>,
startTime = new Date().getTime();
return function () {
return baseTime + (new Date().getTime() - startTime);
};
}());
var calculateTotalWords = function() {
var currentServerTime = getServerTime();
var start = new Date(2004, 0, 1);
var wordsPerYear = 500000;
var SecondInYear = 31556926;
var wordsPerSecond = wordsPerYear / SecondInYear;
var delay = (currentServerTime - start.getTime()) /1000;
var count = delay * wordsPerSecond ;
return Math.round(count);
}
var interval = setInterval(function(){
var count = calculateTotalWords();
document.getElementById("carb").innerHTML = count;
}, 1000);
</script>
</head>
<body>
<div class="count">
<span id="carb">
Loading Word Count...
</span>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.