简体   繁体   English

js代码错误

[英]Error in js code

Can someone tell me why this JS code do not work? 谁能告诉我为什么这个JS代码不起作用?

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); setInterval("stampajDatum()", 1000);函数名称周围的引号setInterval("stampajDatum()", 1000); (Making it setInterval(stampajDatum(), 1000); ) (将其setInterval(stampajDatum(), 1000);

I don't usually use setInterval() , but I know that setTimeout() works. 我通常不使用setInterval() ,但是我知道setTimeout()可以工作。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM