Search code examples
javascriptjquerytampermonkey

How to check if a value isn't changed in between <span> tag


The page looks like:

<html>
  <span id="somespan">1000</span>
</html>

The value of somespan increases every 1 or 2 minutes.

With Javascript/JQuery, how can I check if the value is same or increased every 5 minutes.

I mean at 16:00 the value is 1000 and 2 minutes later so at 16:02 its 1200.
How can I check if its changed.

I wanna make something like:

var somespan = $("#somespan").text();

if(somespan isnt changed) {
  #console.log('still same.')    
}

The platform i will use this code is Google Chrome -> Tampermonkey


Solution

  • You can implement a MutationObserver, but this will do as well.

    var current_value = null;
    setInterval( function() {
      if (current_value != null) {
        if (current_value != $('#somespan').text()) {
          console.log('Value has changed!');
        }
      }
      current_value = $('#somespan').text();
    }, 1000 );
    
    // For testing only
    $('input').on('input', function() {
      $('#somespan').text( $(this).val() );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span id="somespan">1000</span>
    
    <!-- For testing only -->
    <br/>
    <input type="text" value="1000">

    via MutationObserver (no polling required)

    const observer = new MutationObserver(function(mutations) {
      for (const mutation of mutations) {
        if (mutation.type === 'childList') {
          console.log('Value has changed!')
        }
      }
    });
    
    observer.observe(document.querySelector('#somespan'), {childList: true});
    
    // For testing only
    document.querySelector('input').addEventListener('input', function() {
      document.querySelector('#somespan').innerHTML = this.value;
    });
    <span id="somespan">1000</span>
    
    <!-- For testing only -->
    <br/>
    <input type="text" value="1000">