Mare Mare - 6 months ago 25
Javascript Question

Error in js code

Can someone tell me why this JS code do not work?

It should print time every second:

function stampajDatum(){
var now = new Date();
var sat = now.getHours();
var mins = now.getMinutes();
var sec = now.getSeconds();
document.write(sat + ":" + mins + ":" + sec);
}
setInterval("stampajDatum()", 1000);

Answer
function stampajDatum(){
    var now = new Date();
    var sat = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    document.write(sat + ":" + mins + ":" + sec);// the problem is here
    //This writes content to a place after script block
    //if the script is in head then nothing is visible.
    //use something like this:
    //document.getElementById('timer').innerHTML = sat + ":" + mins + ":" + sec;
}
setInterval("stampajDatum()", 1000);//This is OK but setInterval(stampajDatum, 1000); is better. 
//Note that there is no () after stampajDatum