javascript - 函数 "setSeconds( )"不适用于 p5.js Web 编辑器

标签 javascript date p5.js seconds

如您所料,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/

相关文章:

javascript - 从 JavaScript 数组中删除对象?

javascript - 如何将append与getJSON一起使用

java - 使用 Java 查询 MongoDb 的日期范围

php - 如何在 PHP 中使用 date_default_timezone_set() 函数和 +1 天的日期

javascript - 未捕获的TypeError : Cannot read property 'image' of undefinded (p5.js)

javascript - 重新启动我的绘图功能不起作用

c# - 如何通过 SignalR 实现 'Who is typing' 功能?

javascript - 多次触发全局混合 - Vue

mysql - 给定一个日期,在 MySQL 非线性中查找上一个和/或当前和下一个 x# 日期

javascript - p5.j​​s 使用if语句不满足条件时画框