0
<script>
window.onload=function(){
function nowTime(){
var s=0,m;
(function(){
s++;
m=Math.floor(s/60);
document.getElementById('t').innerHTML=(Math.floor(m/60))+':'+(m%60)+':'+(s%60);
setTimeout(arguments.callee,1000);
})();}
nowTime();}
</script>
<div id="t"></div>

这是为了计时,即计算经过了多少秒。
它显示在 HH:MM:SS 中。
谁能缩短或加速它(我的意思是更好的性能)?

此代码每 15 分钟有 100 毫秒的延迟。以下答案具有类似的时间延迟。这段时间无关紧要。如果需要,校准时间非常容易。

4

4 回答 4

2
window.onload = function() {
    var s = 0, m, el = document.getElementById('t');
    (function next() {
        el.innerHTML = ~~((m = ~~(++s / 60)) / 60) + ':' + (m % 60) + ':' + (s % 60);
        setTimeout(next, 1000);
    })();
}
  1. Don't use arguments.callee, it's deprecated.
  2. Cache the DOM element.
  3. Math.floor can be replaced by ~~.
  4. Assigning a variable is an expression, which returns the value of RHS, so you can put m = ~~(++s / 60) in the first use of m.

And then you can uglify it (154 chars):

window.onload=function(){var n,t=0,e=document.getElementById("t")
!function o(){e.innerHTML=~~((n=~~(++t/60))/60)+":"+n%60+":"+t%60,setTimeout(o,1e3)}()}

Working demo: http://jsfiddle.net/PN9An/

于 2013-05-29T08:49:59.247 回答
1

全部写入一行将导致更少的行数:

<script>window.onload=function(){function nowTime(){var s=0,m;(function(){s++;m=Math.floor(s/60);document.getElementById('t').innerHTML=(Math.floor(m/60))+':'+(m%60)+':'+(s%60);setTimeout(arguments.callee,1000);})();}nowTime();}</script><div id="t"></div>
于 2013-05-29T08:46:07.160 回答
1

-1 行

window.onload = function () {
    function nowTime() {
        var s = 0,
            m;
        (function () {
            m = Math.floor(s / 60);
            document.getElementById('t').innerHTML = (Math.floor(m / 60)) + ':' + (m % 60) + ':' + (++s % 60);
            setTimeout(arguments.callee, 1000);
        })();
    }
    nowTime();
}

编辑:删除多余的函数定义>调用(总共-3行)

window.onload = function () {
        var s = 0,
            m;
        (function () {
            m = Math.floor(s / 60);
            document.getElementById('t').innerHTML = (Math.floor(m / 60)) + ':' + (m % 60) + ':' + (++s % 60);
            setTimeout(arguments.callee, 1000);
        })();
}
于 2013-05-29T08:44:45.557 回答
0

来了,先生:

var node=document.querySelector("#id");
var s=0,t={h:3600,m:60,s:1};
setInterval(function(){
  var r=s++;
  node.value=['h','m','s'].map(function(k){var v=Math.floor(r/t[k]);r-=v*t[k];return v+k;}).join("");
},1000);

我选择了一个输入元素来发送文本结果。我不确定您要定位哪种类型的元素,因此您可能需要在必要时更改node.valuenode.textContent

于 2013-05-29T09:06:12.707 回答