user3826891 user3826891 - 1 month ago 8
Javascript Question

Shorten js script using $.each function

I have the following .js code which reads a json file to update the values in the html every minute.

function updateData() {
$.ajaxSetup({ cache: false });
$.getJSON("data/data.json", function(result){
setTimeout(updateData, 60000);

Can this be rewritten in a shorter way using the $.each() function?


It can be improved using a simple for loop:

$.ajaxSetup({ cache: false }); // 1

function updateData() {
  $.getJSON("data/data.json", function(result) {
    for (var i = 1; i<= 9; i++) {
      $('#id' + i).empty().append(result['id' + i]); // 2

    setTimeout(updateData, 60000); // 3

However, accessing the DOM by concatenated IDs does not look good.
For example, you can try to implement it using CSS classes and data-attributes.

Some minor improvements:

  1. ajaxSetup can only be initialized once, you don't need to call it every time.
  2. You probably don't need to empty() and append() at the same time. If it is a text, you can simply use .text(), or .html() for HTML.
  3. It is a good idea to call setTimeout in your getJSON callback so that it updates data in 60 seconds after a previous request is completed, better in .always() handler. Imagine that one of your clients has very slow connection and it takes more than 60 seconds to load this JSON. It will lead to unexpected results.