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);
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();
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.