从时间戳开始经过的Javascript时间 [英] Javascript time passed since timestamp
问题描述
我试图通过将某些信息存储在变量中来缓存一些信息。
如果过了2分钟,我想得到实时值(调用url)。
如果2分钟没有通过,我想从变量中获取数据。
I am trying to "cache" some information by storing it in a variable.
If 2 minutes have passed I want to get the "live" values (call the url).
If 2 minutes have not passed I want to get the data from the variable.
我基本上想要的是:
if(time passed is less than 2 minutes) {
get from variable
} else {
get from url
set the time (for checking if 2 minutes have passed)
}
我是尝试计算时间,如
if((currentime + 2) < futuretime)
但它对我不起作用。
有人知道如何正确检查自上次执行代码后是否已经过去2分钟?
but it wouldn't work for me. Anybody know how to properly check if 2 minutes have passed since the last executing of the code?
TL; DR:想检查是否已经过了2分钟使用IF语句。
TL;DR: Want to check if 2 minutes have passed with an IF statement.
推荐答案
将算法转换为有效的javascript,你可以这样做:
Turning your algorithm into working javascript, you could do something like this:
var lastTime = 0;
if ( Math.floor((new Date() - lastTime)/60000) < 2 ) {
// get from variable
} else {
// get from url
lastTime = new Date();
}
你可以把 if
阻止函数,并在想要从变量或url获取信息的任何时候调用它:
You could put the if
block in a function, and call it anytime you want to get the info from either the variable or the url:
var lastTime = 0;
function getInfo() {
if ( Math.floor((new Date() - lastTime)/60000) < 2 ) {
// get from variable
} else {
// get from url
lastTime = new Date();
}
}
希望有所帮助。
这篇关于从时间戳开始经过的Javascript时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!