obj.document.getElementById('clock');
Since obj
is undefined at this point, it will throw a referenceError
. Perhaps you meant:
var obj = document.getElementById('clock');
if (obj != "false")
This will most likely not work, since you're comparing to a string. If you want to check whether obj
is an object or null
, you can use
if (obj)
obj = mytime;
this will not modify the original obj
, but rather overwrite the variable holding a reference to it. Perhaps you wanted
obj.innerHtml = mytime;
also change the HTML from
<p id="clock">The time according to your PC is :</p>
to
<p>The time according to your PC is :<span id="clock"></span></p>
so that you don't overwrite the text but do overwrite the clock.
onclick="setTimeout('"
...
onclick="int=window.clearInterval(int)"
there is a part missing:
onclick="timer = setInterval(clock, 1000)"
...
onclick="window.clearInterval(timer)"
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 clearInterval
is not particularly useful since the argument to it should be the value returned by setInterval
.
Also note the distinction between setTimeout
(which will call a function once) and setInterval
(which will call it repeatedly).
Also note that the timer
variable 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 of body
) (and assign the correct IDs to both inputs):
(function(){ //create a scope
var timer; //create a local variable
document.getElementById("clock-start")
.addEventListener("click", function(){
if(!timer) timer = setInterval(clock, 1000);
})
document.getElementById("clock-stop")
.addEventListener("click", function(){
clearInterval(clock);
})
})() // remember to call our anonymous function
or the jQuery version (anywhere in the document):
$(document).ready(function(){ //execute on DOM ready
var timer;
$("#clock-start").on("click", function(){
if(!timer) timer = setInterval(clock, 1000);
})
$("#clock-stop").on("click", function(){
clearInterval(clock);
})
});