在Float32Array中,日期只能作为值设置一次。进一步的更新没有区别。运行下面的代码段,然后查看(Chrome,Firefox,IE)。

有解决方法吗?我必须将当前时间作为Float32Array的值之一。

var d1 = document.querySelector('#d1');
var d2 = document.querySelector('#d2');
var d3 = document.querySelector('#d3');

var fa = new Float32Array(1);
var date;
setInterval(function() {
  date = Date.now();
  fa[0] = 52343225; // another value to clear the previous value - doesn't help
  fa[0] = date;

  d1.textContent = date;
  d2.textContent = fa[0];
  d3.textContent = date - fa[0];

}, 50);
<div>Date: <span id="d1"></span>
</div>
<div>Float32Array value: <span id="d2"></span>
</div>
<div>Difference: <span id="d3"></span>
</div>

<p>As you can see above the date in Float32Array is not changing. Initially the date is set in the FUTURE</p>

new Date().getTime() // gives the same result
performance.now() // works correctly

有趣的是,日期总是在打开标签页后的第一分钟设置。即使页面刷新也不会重置此计时器。仅打开新标签并运行脚本才能启动倒计时。

最佳答案

看来32位浮点数不能正确处理日期值。我切换到一个float64,它工作得很好。

var d1 = document.querySelector('#d1');
var d2 = document.querySelector('#d2');
var d3 = document.querySelector('#d3');

// CHANGED HERE
var fa = new Float64Array(1);
var date;
setInterval(function() {
  date = Date.now();
  fa[0] = 52343225; // another value to clear the previous value - doesn't help
  fa[0] = date;

  d1.textContent = date;
  d2.textContent = fa[0];
  d3.textContent = date - fa[0];

}, 50);
<div>Date: <span id="d1"></span>
</div>
<div>Float32Array value: <span id="d2"></span>
</div>
<div>Difference: <span id="d3"></span>
</div>

10-06 00:46