0

I'm working on an app that uses an html/javascript framework. The app loads in pages from a database using a PHP script and a $.get call whenever a page is shown like so:

    // Set lastTime var for counting the amount of time passed since $.get
    var lastTime = 0;

    // Amount of minutes before new $.get
    var timeOut = 1;

    // Cache
    var cache = [];

    function load_page(page, location) {
        // Check if 1 minute passed
        if ( Math.floor((new Date() - lastTime)/60000) < timeOut ) {
            // Get cache
            $(location+' .homeText').html(cache[page]);
        } else {
            // Get URL
            $.get('http://mydomain.com/get_posts.php?page='+page, function(data) {          
                $(location+' .homeText').html(data);
            });

            // Fill array with data
            cache.push();

            // Set lastTime var for checking how long since URL fetch
            lastTime = new Date();
        }
    }

It's almost done but I can't figure out how to populate my cache variable. I want to populate it in such a way that I can use the page variable as a key to keep everything as dynamic as possible. I know how to fill an array with data but I can't figure out how to give it a specific key and value.

5
  • Do you have a sample/format of data (as returned by $.get() )? Commented May 20, 2014 at 10:04
  • it should be cache.push(data); Commented May 20, 2014 at 10:05
  • @user3558931 That's kinda difficult, since the result is from a post in wordpress. In the end it's just text within paragraph tags though. Commented May 20, 2014 at 10:07
  • @AamirAfridi But then it would have keys like 0, 1 and 2 instead of the page variable as a key. Commented May 20, 2014 at 10:07
  • just use cache = data? Commented May 20, 2014 at 10:08

4 Answers 4

2

Something like this

var cache = {};

To get from cache

if (cache[page] !== undefined) {...

To populate the cache

cache[page] = data;
Sign up to request clarification or add additional context in comments.

Comments

1

In Javascript, most people will use a simple Object to mimic the behavior of an associative array.

First, change your cache definition to be an empty object:

// Cache
var cache = {};

Then when you want to save your loaded HTML, just do this:

cache[page] = data;

Now, although you don't specify, I think you also have a bug in your logic -- you only have one lastTime variable, but I would think you would be keeping a 1 minute timer separately for each potential page load. In that case, you might have something more like this:

cache[page] = {
  html: data,
  expires: new Date().getTime() + 60000
};

To make it clear, here's how I might rewrite your function snippet, using the cache object to store both the HTML data and the time the data should expire.

// Cache
var cache = [];

function load_page(page, location) {
  var now = new Date().getTime();

  // Check for a previously cached value
  var result = cache[page];

  if (result && result.expires > now) {
    // Use the cached HTML data
    $(location + ' .homeText').html(result.data);
  } else {
    // Get URL
    $.get('http://mydomain.com/get_posts.php?page=' + page, function (data) {
      $(location + ' .homeText').html(data);

      // Store the HTML and its expiration time
      cache[page] = {
        data: data,
        expires: now + 60000
      };
    });
  }
}

1 Comment

I actually had to switch the accepted answer. I ran into this bug just now and didn't know how to solve it. 10/10 on going the extra mile.
0

There is no such things as an associative array in JavaScript. Here is an interessting blog post about that : http://blog.kevinchisholm.com/...

But you can do this thought :

cache.push({key:value,key:value});

Comments

0

Alternatively, if for any reason you had to use an array cache then you would use the following:

// Set lastTime var for counting the amount of time passed since $.get
var lastTime = 0;

// Amount of minutes before new $.get
var timeOut = 1;

// Cache
var cache = [];

function load_page(page, location) {
    // Check if 1 minute passed
    if ( Math.floor((new Date() - lastTime)/60000) < timeOut ) {
        // Get cache
        $(location+' .homeText').html(cache[page]);
    } else {
        // Get URL
        $.get('http://mydomain.com/get_posts.php?page='+page, function(data) {          
            $(location+' .homeText').html(data);

            // Fill array with data
            var oPage = {};
            oPage[ page ] = data;
            cache.push( oPage );

            // Set lastTime var for checking how long since URL fetch
            lastTime = new Date();

        });
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.