【问题标题】:Function "setSeconds( )" does not work with p5.js web Editor函数“setSeconds( )”不适用于 p5.js Web 编辑器
【发布时间】:2019-06-08 10:21:18
【问题描述】:

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

我想编写一些代码来计算角度(从水平方向)和移动物体的方向。尝试在我的代码中任何可以想象的地方插入函数,甚至将我的 sn-p 代码与其他代码隔离,以确保没有不需要的外部代码(如其他变量)影响它。

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() 方法设置日期对象的秒数。我测试了它并且它正在工作。你想用这个功能实现什么? @大卫

标签: javascript date p5.js seconds


【解决方案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>

【讨论】:

  • 我很感激。但是您能否详细说明为什么网络编辑器不包含该功能?我偶然发现了这个编辑器,假设它基本上是 Javascript?如果不是,那是什么?如果它没有一些标准的Javascript函数,为什么叫“p5.js”呢?
  • 我刚刚在 p5.js 中测试了您的代码,它完全按预期工作。 editor.p5js.org/henslersoftware/sketches/ZYsINHkkK
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多