如您所料,setSeconds();通常会返回并将当前日期的秒数传递给参数内的指定值。但无论我在 p5.js Web 编辑器中尝试什么,它都绝对没有效果。
我想编写一些代码来计算移动物体的 Angular (与水平面的 Angular )和方向。尝试在我的代码中任何可以想象到的地方插入该函数,甚至将我的代码片段与其余代码片段隔离,以确保没有不需要的外部代码(如其他变量)影响它。
function seconds_Passed()
{
timePassed = new Date()
timePassed.setSeconds(0); //Has no effect even though many js examples show
//this as the way to do it.
secondsPassed = timePassed.getSeconds();
console.log(secondsPassed);
}
没有错误消息。 预期结果是:当我运行代码时,秒数始终从 0 开始,而不是您在桌面时钟上看到的实际实时秒数。
最佳答案
setSeconds()
不是 p5.js 函数,这是一个标准 JS 方法,根据本地时间设置指定日期的秒数 MDN Docs .
所以解析:-
function seconds_Passed()
{
timePassed = new Date()
timePassed.setSeconds(0); //Has no effect even though many js examples show
//this as the way to do it.
secondsPassed = timePassed.getSeconds();
console.log(secondsPassed);
}
始终返回 0 秒。
如果您需要获取两个事件之间的时间,则需要捕获两个时间戳。
例如:-
function seconds_Passed()
{
const date = new Date();
const start = date.getTime();
console.log("Start UNIX time " + start);
setInterval(() => {
const nowDate = new Date();
const timeParsed = (Math.round((nowDate.getTime() - start) / 1000));
console.log(timeParsed + ' Seconds parsed since script started');
}, 3000)
}
seconds_Passed()
另一个显示按钮点击的示例:-
const date = new Date();
const start = date.getTime();
function buttonClicked()
{
const nowDate = new Date();
const timeParsed = (Math.round((nowDate.getTime() - start) / 1000));
console.log(' It took you ' + timeParsed + ' second to click the button');
}
<button onclick="buttonClicked()">
Click me
</button>
关于javascript - 函数 "setSeconds( )"不适用于 p5.js Web 编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505467/