函数“ setSeconds()”不适用于p5.js Web编辑器

时间:2019-06-08 10:21:18

标签: javascript date p5.js seconds

如您所料,setSeconds();通常会返回并将当前日期的秒数设置为参数内部的指定值。但是无论我在p5.js网络编辑器中尝试什么,它都完全无效。

我想编写一些代码来计算移动物体的角度(相对于水平方向)和方向。试图在我的代码中可以想象到的任何地方插入该功能,甚至将我的代码片段与其余代码隔离开来,以确保没有有害的外部代码(如其他变量)影响它。

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开始,而不是您在桌面时钟上看到的实际经过的秒数。

1 个答案:

答案 0 :(得分:1)

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>