0

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);
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Mare
  • 81
  • 2
  • 7
  • 2
    Calling `document.write()` after the document has finished loading will reset it, removing all elements that existed. [What are alternatives to document.write?](http://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write) – Jonathan Lonowski May 21 '16 at 23:47
  • Also, providing a string to `setInterval()` [is usually considered bad practice](http://stackoverflow.com/questions/6081560/is-there-ever-a-good-reason-to-pass-a-string-to-settimeout), for the same reasons as `eval()` – [`setInterval(stampajDatum, 1000)`](http://stackoverflow.com/questions/4506074/settimeout-with-string-or-anonymous-function-reference-speedwise). – Jonathan Lonowski May 21 '16 at 23:52
  • Why did you pass in a string into `setInterval`? that is incorrect, the parameter is a function. – t0mm13b May 21 '16 at 23:54
  • @t0mm13b It's valid – [`setInterval(code, delay)` syntax](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) – just not recommended or ideal. – Jonathan Lonowski May 21 '16 at 23:57
  • The function declaration looks valid, but the reality is, it can be anything, even a string..despite the nomenclature declaring convention as `code`. – t0mm13b May 22 '16 at 00:58

2 Answers2

0

The first message I'm getting in my console is about that implied eval. Take away the quotes around the function name in setInterval("stampajDatum()", 1000); (Making it setInterval(stampajDatum(), 1000);)

I don't usually use setInterval(), but I know that setTimeout() works. Here's an example:

function stampajDatum(){
    var now = new Date();
    var sat = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    document.write(sat + ":" + mins + ":" + sec);
    setTimeout(stampajDatum(), 1000);
}
stampajDatum();
0
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
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36