Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript time passed since timestamp

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.

What I basicly want is:

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)
}

I've tried calculating the time with things like

if((currentime + 2) < futuretime)

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: Want to check if 2 minutes have passed with an IF statement.

like image 346
Parrotmaster Avatar asked Mar 07 '13 13:03

Parrotmaster


1 Answers

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();
}

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();
    }
}

Hope it helps.

like image 81
rdleal Avatar answered Oct 07 '22 04:10

rdleal