Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中获得随机秒与现在秒之间的差异_Javascript - Fatal编程技术网

在Javascript中获得随机秒与现在秒之间的差异

在Javascript中获得随机秒与现在秒之间的差异,javascript,Javascript,我有一点javascript,它生成一个随机数,以毫秒计(0到10秒之间) 除此之外,我还使用getTime()方法设置starttimer,稍后再设置stoptimer 因此,我希望获得时差(stoptimer starttimer)和随机选择的毫秒之间的毫秒差 比如:随机毫秒是1.3秒,时差是1。用户关闭0.3秒 millisecondsToPress = Math.floor((Math.random()*100)+1)*1000; startTime = attempt.getCurr

我有一点javascript,它生成一个随机数,以毫秒计(0到10秒之间)

除此之外,我还使用
getTime()
方法设置starttimer,稍后再设置stoptimer

因此,我希望获得时差(
stoptimer starttimer
)和随机选择的毫秒之间的毫秒差

比如:随机毫秒是1.3秒,时差是1。用户关闭0.3秒

millisecondsToPress = Math.floor((Math.random()*100)+1)*1000; 
startTime = attempt.getCurrentTime();
稍晚一点,一个showresult被调用,它会停止时间并进行计算

stopTime = attempt.getCurrentTime();
showResult();
下面是getTime函数:

var d = new Date();
return d.getTime();
以及现在的显示结果(这是错误的:-p) var secondsPressed=this.stopTime-this.startTime

if (secondsPressed >= this.millisecondsToPress) {
    //The timedifference is bigger than the toPress. The player overshot!
    result = secondsPressed - this.millisecondsToPress;
} else {
    //The player undershot
    result = this.millisecondsToPress - secondsPressed;
}

我很可能对毫秒或某些东西有错误(*1000或*100等)

您的随机时间生成器提供的值在1到100秒之间,并且仅在整秒内,因为
*1000
发生在随机时间四舍五入之后。您可能想要:

var millisecondsToPress = Math.floor(10000 * Math.random());
如果您只关心错误的大小,请使用
Math.abs()

将除法转换回秒

要以毫秒为单位获取当前时间的数值,只需使用
+new Date()

在较旧的浏览器上,或者在较新的浏览器上(
Date.now()
)(后者效率更高,因为它不实例化对象)。

tartTime
只是问题中的一个输入错误?
Math.floor((Math.random()*100)+1)*1000将生成1000到101000之间的随机数。。。对于介于0和10000之间的对象,请使用
Math.floor(Math.random()*10000)
@ic3b3rg上限实际上是100,而不是101-
数学地板(0.9999*100)==99
@Alnitak这是真的!我一直认为1是上限。。。现在我知道Math.random()
返回一个浮点伪随机数,范围为[0,1],即从0(包括)到但不包括1(排除)
。谢谢。Math.abs()方法非常方便。谢谢!顺便说一下,我想要
Math.floor((Math.random()*100)+1)*100+1
是干什么用的。是的,没有+1它也能工作。我真的只想要一个介于0.0和9.9之间的数字。这就是经过一段时间后它现在要做的很多点心:D
result = Math.abs(secondsPressed - this.millisecondsToPress) / 1000.0