简体   繁体   中英

Check is class exist longer than X in javascript

I wrote simple monitor which check few things on my networks and display status - I am fetching statuses using ajax. When something is wrong I am adding class error to div which is displaying current status.

Later I add player with error sound when class error is present it plays music. I set 3 second interval and thats all.

But not always error mean error, sometimes I recive false warning. Now I am looking for way to play sound when class error exists longer than XX seconds.

I suppose I have to wrote function with interval 1s, add every hit 1 to temp variable and check is variable bigger than else clean temp variable, but maybe is there more elegant way.

i guess it should work

$('.error').each(function(){
var e = $(this)
setTimeout(function(){
if (e.attr('class') == 'error'){
e.attr('class','error-with-sound');
}
},2000);
});

You should take two vars store the current time at their respective events.

var oldTime, newTime;

// Now when you are adding the class
$(something).addClass("someclass");
oldTime = new Date().getTime(); // Store the timestamp.

//And when you are removing the class
$(something).removeClass("someclass");
newTime = new Date().getTime(); // Store the timestamp.

// Now you check whether class was added for more then XX Seconds
var _diff = (newTime - oldTime)/1000; // Diference is in seconds.

There is no direct way for that, you can add timestamps in your class with separator something like error_1448953716457 and later you can split that and can compare with current timestamps

 $('#na').click(function () { var t = new Date().getTime(); $('h1').addClass("error_" + t); }); $('#nr').click(function () { var t = new Date().getTime(); $("[class^=error]").each(function (e) { $("span").html("Diff. Seconds : " + ((t - ($(this).attr('class').split(' ').pop().split('_')[1])) / 1000).toString()); }); }); 
 input { width:100px; } .error { color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <h1>.addClass()</h1> <input id="na" value="Add Class1" type="button" /> <br/> <input id="nr" value="Calculate Diff" type="button" /> <span></span> 

If you want to track .error elements on the page, set an independent interval that looks for those elements and tracks the ones it has seen before by setting an attribute or data value in jquery.

Remember to clearInterval(interval) if you no longer need to check for .error elements.

(function ($) {
  // set constants in milliseconds as desired
  var INTERVAL_LENGTH = 100, // how often to check DOM for error elements
      NOTIFY_AFTER = 3000;   // handle error after this length

  // check for .error elements and handle those that have been around for a while
  var interval = setInterval(function () {
    var now = Date.now();
    $(".error").each(function () {
      var t = $(this).data('error-time');
      if(t) {
        if(now - t > NOTIFY_AFTER) {
          handleErrorElement(this);
        }
      }
      else {
        $(this).data('error-time', now);
      }
    });
  }, INTERVAL_LENGTH);

  function handleErrorElement(elem) {
    // do what you need for error elements visible past a threshold
    console.log("handling error element: ", elem);
  }

})(jQuery);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM