i got a task that ask me to create a page, which can display a clock after
the user click on the start button and stop when click the stop button
The clock need to display inside a “span” tag because i need the DOM1 method.
So my Code currently look’s like this
*I had already fix this.
function clock()
{
var obj = document.getElementById('clock');
if (obj)
{
var now = new Date();
var mytime = now.getHours()+":"+now.getMinutes()+"."+now.getSeconds();
obj.innerHTML = mytime;
}
}
</script>
</head>
<body onload="clock()">
<table>
<h1>A live clock in JavaScript</h1>
<p>The time according to your PC is :<span id="clock"></span></p>
<input type="button" name="clickMe" value="Start the clock"
onclick="timer = setInterval(clock, 1000)"/>
<button onclick="window.clearInterval(timer)">Stop</button>
</table>
</body>
</html>
Since
objis undefined at this point, it will throw areferenceError. Perhaps you meant:This will most likely not work, since you’re comparing to a string. If you want to check whether
objis an object ornull, you can usethis will not modify the original
obj, but rather overwrite the variable holding a reference to it. Perhaps you wantedalso change the HTML from
to
so that you don’t overwrite the text but do overwrite the clock.
there is a part missing:
where the first argument is the function being called repeatedly, and the second argument is the frequency of the calls in miliseconds. Also note that the return value of
clearIntervalis not particularly useful since the argument to it should be the value returned bysetInterval.Also note the distinction between
setTimeout(which will call a function once) andsetInterval(which will call it repeatedly).Also note that the
timervariable now resides in the global scope. This could be a problem in larger projects. You also have a problem if you start the timer several times as you can’t stop it now. Consider this instead (at the end ofbody) (and assign the correct IDs to both inputs):or the jQuery version (anywhere in the document):