开发者

javascript timer error

I started working on a timer to show how long people have been on my page. The problem is that instead of counting the seconds, it just keeps adding zeros to the end. Can anyone show me where I went wrong?

<script language="javascript">
<!--
var seconds = 0
var minutes = 0
document.getElementById('timer').innerHTML = '0'
function Timer() {
    if ( seconds < 10 ) {
        seconds = "0" + seconds
    }
    else if ( minutes < 10 ) {
        minutes = "0" + minutes
    }
    else if ( seconds >= 59 ){
        seconds = 0
        minutes += 1
    }
    else
        seconds += 1
        document.getElementById('timer').innerHTML = "You've been on my blog for    "+minutes+" : "+seconds+" minutes."
        setTimeout("Timer()",10开发者_如何学运维00)
}
//-->
</script>


Well yes, because you're concatenating a string. The + operator does both concatenation and addition.

"0" + foo  // concatenate the string "0" and foo
0 + foo    // add foo to 0 (given that both are numbers)

You're going about the timer the wrong way though. Your script is not guaranteed to execute on time, any slight delay in execution will give you accumulative the wrong value. The right way to do a timer is to take a fixed start time and use that as the base to calculate the difference every second or so.

var start = Date.now();
function timer() {
    alert(((Date.now() - start) / 1000) + ' seconds elapsed');
}
setInterval(timer, 1000);


You're switching the variable type for seconds from being:

var seconds = 0  // integer type
....
seconds = "0" + seconds // now seconds is holding a string!

seconds (and minutes) should only be integers.

Also, just focus on the seconds. Later, divide it by 60 to display number of minutes. seconds % 60 will be the remaining number of sec.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜