我在javascript中的setInterval()函数遇到问题,该函数将一次打印到我的页面,并且不会继续这样做。我想知道这是否是浏览器问题或我做错了什么。
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.write(hours + ":" + minutes + ":" + seconds + "<br/>");
}
setInterval("printTime()", 1000);
最佳答案
除了使用"functionName()"
而不是仅使用functionName
的不良做法之外,如果间隔超出页面加载范围,则该代码将永远无法工作。document.write
将在加载后擦除页面
这是一个更好的解决方案:
<div id="time"></div>
<script>
function pad(str) { return ("0"+str).slice(-2)}
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.getElementById("time").innerHTML+=pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + "<br/>";
}
setInterval(printTime, 1000);
</script>
关于javascript - setInterval遇到问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31617775/