问题
Hi i'm quite new to java script and for some reason setInterval
does not seem to work when i run this code on firefox
. Ive tried running it on Microsoft
edge but it still does not work. It just prints out the date once but does not continue from there. Any help would be appreciated.
Thanks!
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--Intervals with Date/time-->
function printTime(){
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var seconds = now.getSeconds();
document.write(hours+":"+mins+":"+seconds+"<br \>");
}
setInterval("printTime()", 1000);//in ms
</script>
</body>
</html>
回答1:
document.write(
is 1990's code - don't use it at all ... also setInterval("printTime()", 1000)
in code less than 30 years old is written setInterval(printTime, 1000)
function printTime(){
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var seconds = now.getSeconds();
document.body.innerHTML += (hours+":"+mins+":"+seconds+"<br \>");
}
setInterval(printTime, 1000);//in ms
The reason document.write fails is documented here
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
来源:https://stackoverflow.com/questions/51094528/setinterval-not-working-on-firefox