axchink
axchink

Reputation: 179

JavaScript: Counter & IF / Else

I am new to JavaScript and back-end coding as well. I need help with initiating counter. The code I have written below does the following things.

  1. Loop through an external JSON file that has set of objects (numbers) and compares its previous value to the current value
  2. If the current value is less than or greater than the previous value, it changes the image

What I want to do is, when the current value is less than or greater than the previous value, it should change the background color and start a counter called counterAlert. This counter should count up to 10 seconds and change the background color back to the original color but, during this 10 second time frame, the function should continue to loop through the JSON file and if it hits the condition where current value is again, greater than or less than the previous value, the counter should reset.

JavaScript code I have to loop through the JSON file is the following

var counter = 0; // Trial 
var counterAlert = 0

$(document).ready(function () {       

  $.ajaxSetup({ cache: false });

       myJson();

    });

// Below is the function to draw data from Json        
function myJson() {

    $.getJSON("Janus.json", function (response) {

        var i = 1380; //start demo at last hour of data.

            var looping = setInterval(function () {
            var TrialCount = response.length;
            var Info = response[counter];
            var Checker_Data = Info.WOB;

            Checker_Data = Checker_Data.toFixed(2);

            CompareChecker();

            function CompareChecker() {
                if (counter == 0) {
                    prev_Checker_Data = Checker_Data;
                }

                if (Checker_Data > prev_Checker_Data) {
                    if ((Math.abs(Checker_Data - prev_Checker_Data) >= prev_Checker_Data / 2 ))
                    document.getElementById("Checker_img").src = "img/yeltri.png",
                    document.getElementById("CheckerValue").style.backgroundColor = '#006699';

                    else if ((Math.abs(Checker_Data - prev_Checker_Data) <= prev_Checker_Data / 2))
                        document.getElementById("Checker_img").src = "img/grnsqr.png";
                }

                else if (Checker_Data < prev_Checker_Data) {
                    if ((Math.abs(Checker_Data - prev_Checker_Data) >= prev_Checker_Data / 2))
                    document.getElementById("Checker_img").src = "img/yeltriDn.png";
                    else if ((Math.abs(Checker_Data - prev_Checker_Data) <= prev_Checker_Data / 2))
                        document.getElementById("Checker_img").src = "img/grnsqr.png";
                }

                prev_Checker_Data = Checker_Data;
            }

            document.getElementById("Checker").innerHTML = Checker_Data


            counter++;
            if (counter == TrialCount) clearInterval(looping);


        }, 10);
    });
};

I am thinking, to do what I want, I need to insert another function under the function CompareChecker()'s If statement such that

    if (Checker_Data > prev_Checker_Data) {
    if ((Math.abs(Checker_Data - prev_Checker_Data) >= prev_Checker_Data / 2 ))
    document.getElementById("Checker_img").src = "img/yeltri.png",
    document.getElementById("CheckerValue").style.backgroundColor = '#006699',
checkerValue_Timer();
    function checkerValue_Timer(){
    counterAlert++;
     if (counterAlert == 10)
     document.getElementById("CheckerValue").style.backgroundColor = '#cecece';
}
setInterval(CheckerValue_Timer, 1000);

but I am not sure, please help

Upvotes: 0

Views: 1239

Answers (1)

Yogi
Yogi

Reputation: 7184

The question is not at all clear, especially the logic. The original code uses a sample rate of 10 milliseconds, yet requires a 10 second reset timer. So just to test this we need to generate a data set with thousands of records and with a minimum of 1000 matching records to trigger a reset.

The example below attempts to break the code into data, timer, and UI functions to make it more manageable. Yet, OP just needs to focus on the timer section which is the controlling logic. Per requirements, mismatching records trigger a UI change. The UI is not reset to the original until after there have been 10 seconds of continuously matching records (+1000 records).

To test, click "Show code snippet" link and then click blue button "Run code snippet"

Update: Modified the code so that the image is toggled by the class name. This is much more efficient than repeatedly setting an image src as done in the original code, i.e., it avoids extraneous server requests.

(function() {

  var DEBUG = true, // false = use json data, true = auto generate data
    DATA_URL = 'janus.json',
    IMAGE_URL = 'https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/',
    INTERVAL = 10,
    TIMEOUT = 10000,
    counter, timerId, response, timerAlert;


  // initialize
  $('#button1').click(function() {
    getData(function(data) {
      response = data;
      startTimer();
    });
  });
  $('#button1').click();


  function startTimer() {

    // reset
    counter = 0;
    timerAlert = 0;
    if (timerId) clearInterval(timerId);

    // start 
    timerId = setInterval(function() {
      counter++;
      if (counter >= response.length - 1) clearInterval(timerId);
      if (parseFloat(response[counter].WOB) != parseFloat(response[counter - 1].WOB)) {
        timerAlert = 0;
        updateUI(false);
      } else {
        timerAlert += INTERVAL;
        if (timerAlert > TIMEOUT) timerAlert = TIMEOUT;
        updateUI(timerAlert >= TIMEOUT);
      }
    }, INTERVAL);
  };



  function updateUI(bOriginal) {
    $('#CheckerValue').css('background-color', (bOriginal ? 'LightGray' : 'SeaGreen'));
    
    
    // $('#Checker_img').attr('src', IMAGE_URL + (bOriginal ? 'status_offline.png' : 'status_online.png'));
    $('#Checker_img').attr('class', 'icon ' + (bOriginal ? 'offline' : 'online'));
    
    
    $('#Checker').html(parseFloat(response[counter].WOB).toFixed(2));
    $('#counter').html(counter);
    $('#timerAlert').html((timerAlert / 1000).toFixed(2) + ' seconds');
    $('#Time').html((new Date()).toLocaleTimeString());
  }


  // get data from server or generate test data when debug true
  function getData(callback) {

    if (!DEBUG) {
      $.ajaxSetup({
        cache: false
      });
      $.getJSON(DATA_URL, callback);
    } else {
      var i, data = [];
      for (i = 0; i < 2500; i++) data.push({
        WOB: (i < 20 ? 100 : i == 1200 ? 100 : 200)
      });
      callback(data);
    }

  }

})();
table {
  border-collapse: collapse;
  width: 400px;
  
  font-family: sans-serif;
  font-size: 14px;
}
td {
  white-space: nowrap;
  padding: 2px;
  border: 1px steelblue solid;
}

.icon {
  background-repeat: no-repeat;
  width: 32px;
  height: 32px;
}
.icon.online {
  background-image: url(https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/status_online.png);
}

.icon.offline {
   background-image: url(https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/status_offline.png);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
  <button id="button1">Start</button>
  <table>
    <tr>
      <td>Checker_Img</td>
      <td id="Checker_img" class="icon offline">
        
      </td>
    </tr>
    <tr>
      <td>CheckerValue</td>
      <td id="CheckerValue"></td>
    </tr>
    <tr>
      <td>Checker</td>
      <td id="Checker">0</td>
    </tr>
    <tr>
      <td>counter</td>
      <td id="counter">0</td>
    </tr>
    <tr>
      <td>timerAlert</td>
      <td id="timerAlert"></td>
    </tr>
    <tr>
      <td>Time</td>
      <td id="Time"></td>
    </tr>
  </table>
  
  
  

Timer Logic:

  function startTimer() {

    // reset
    counter = 0;
    timerAlert = 0;
    if (timerId) clearInterval(timerId);

    // start 
    timerId = setInterval(function() {
      counter++;
      if (counter >= response.length - 1) clearInterval(timerId);
      if (parseFloat(response[counter].WOB) != parseFloat(response[counter - 1].WOB)) {
        timerAlert = 0;
        updateUI(false);
      } else {
        timerAlert += INTERVAL;
        if (timerAlert > TIMEOUT) timerAlert = TIMEOUT;
        updateUI(timerAlert >= TIMEOUT);
      }
    }, INTERVAL);
  };

Upvotes: 1

Related Questions