JavaScript定时响应

时间:2015-09-22 22:11:25

标签: javascript timed

我遇到了一个JavaScript定时输出问题,它表示某种类型的问候,然后是时间。 代码:

{{1}}

预期的输出应该是这样的: Wakey Wakey,/早上/下午/晚上,Person先生。时间是:(时间)。

3 个答案:

答案 0 :(得分:2)

您的代码中有许多未设置的变量,起始}和结尾alert();也都是语法错误。

以下代码已更正,只需将document.write();再次替换为 var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds(); if (hours < 7){timemsg = "Wakey wakey, Mr. Person. The time is: " + hours + ':' + minutes + ':' + seconds} if (hours > 6 && hours <12){timemsg = "Good morning, Mr. Person. The time is: " + hours + ':' + minutes + ':' + seconds} if (hours > 11 && hours <18){timemsg = "Good afternoon, Mr. Person. The time is: " + hours + ':' + minutes + ':' + seconds} if (hours >17){timemsg = "Good evening, Mr. Person. The time is: " + hours + ':' + minutes + ':' + seconds} alert(timemsg);

The time is: " hours + ':'

另外,你经常这样做,所以我认为值得一提。 这样:

The time is: " + hours + ':'

需要

+

查看变量前后的+ 。您需要在字符串中的变量之前和之后添加"Good afternoon, Mr. Person. The time is: " + hours + ':' + minutes + ':' + seconds

旁注:

ecmascript 6的一部分是template strings。这是何时使用它们的一个很好的例子。例如:

`Good afternoon, Mr. Person. The time is: ${hours}:${minutes}:${seconds}`

现在可以写成

{{1}}

这使它更具可读性。请注意此功能支持的浏览器。

答案 1 :(得分:0)

经过几个小时后,我能够解决这个问题:

function startTime() {
    // Clock
    var hello="The time is: ";
    var today=new Date();
    var h=today.getHours();
    var m=today.getMinutes();
    var s=today.getSeconds();
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    // Timed Greeting
    if (h == 6 && m == 30 && s == 0){window.alert("Go to school, dude!")};
    if (h < 7){timemsg = "You're up <B>really</B> early, Mr. Lawrence! "};
    if (h > 6 && h <12){timemsg = "Good morning, Mr. Lawrence! "};
    if (h > 11 && h <18){timemsg = "Good afternoon, Mr. Lawrence! "};
    if (h >17){timemsg = "Good evening, Mr. Lawrence! "};
    document.getElementById('txt').innerHTML = timemsg+hello+h+":"+m+":"+s;
    var t = setTimeout(function(){startTime()},500);
}

function checkTime(i) {
    if (i<10) {i = "0" + i};  // Add zero in front of numbers < 10
    return i;
}

答案 2 :(得分:-1)

试试这个:

image

它应该有用。