gpt4 book ai didi

javascript - 尝试在我的时钟中应用 setInterval 失败

转载 作者:行者123 更新时间:2023-11-30 15:41:04 25 4
gpt4 key购买 nike

我自学 JavaScript 并尝试每天编写一些代码。我目前正在尝试构建一个简单的时钟,但我似乎无法让我的 setInterval 工作。我试过将它放在不同的地方,但我认为它属于“时间”功能,所以应该放在那之后。我想知道它是否与我调用函数的方式有关。我还不完全清楚何时调用哪种方法。指导肯定会受到赞赏。

var dayTime = function() {
// Create a new instance of the Date contructor function.
var date = new Date();

var today = function() {
// Create an array of weekday names
var dayArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// Extract the day. Will return a numeric representation.
var dayIndex = date.getDay();

// Step 4: Use weekday names array with weekday numeric to display text version of weekday.
var today = dayArray[dayIndex];
// Step 5: Place results into span on webpage
var x = document.getElementById("day").innerHTML = today;
}()

var time = function() {

var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

// Set am or pm
var amPm = hours < 12 ? "am" : "pm";

// Set to 12 hour time format
hours = hours > 12 ? hours - 12 : hours;

// Convert midnight until 1am to 12
hours = (hours == 0) ? 12 : hours;

var y = document.getElementById("time").innerHTML = "Current time is " + hours + ":" + minutes + ":" + seconds + " " + amPm;

}()
setInterval(time, 1000);
}
<html lang="en">

<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>

<body onload="dayTime();">
<h1>Simple Date Exercise</h1>
<p>Today is <span id="day"></span>
</p>
<p id="time">00:00</p>
</body>

</html>

最佳答案

setInterval(time, 1000);

setInterval 的第一个参数必须是一个函数。您传递的 time 变量包含……

var time = function() {
// A bunch of statements but no return statement
}()

由于您在它后面加上 (),您将立即调用它,因此返回值 (undefined) 被分配给 time


删除 ()。不要立即调用该函数。

关于javascript - 尝试在我的时钟中应用 setInterval 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com