skip to Main Content

I have a page that contains a div that refreshes every 3 seconds that looks like this:

<script>
$(document).ready(function(){
setInterval(function(){
      $("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>

<div id="here">
/* Div content, contains an html table*/
</div>

I want the refresh script to stop if a certain <td> in the HTML table is clicked. When the user clicks outside of the cell, I want the refresh script to continue running.

Is this at all possible?

2

Answers


    1. Define a start() function
      • Use setInterval to start the counter, remember it’s returned pid
    2. Define a end() function
      • Use clearInterval on the pid to stop the counter
    3. Define a eventListener on all the tr‘s that will call the stop() function
    4. Define a eventListener on document that will call start() if we’re not already counting (!pid) and we didn’t click on a <tr> or <th>:
      ![ 'TD', 'TH' ].includes(e.target.nodeName)
    let pid = null;
    
    const start  = () => {
        console.log('Starting interval action');
        pid = setInterval(() => {
            console.log('setInterval Action')
        }, 3000);
    }
    const stop  = () => {
        console.log('Stopping interval action');
        clearInterval(pid);
        pid = null;
    }
    
    document.addEventListener('click', (e) => {
        if (![ 'TD', 'TH' ].includes(e.target.nodeName) && !pid) {
            start();
        }
    });
    Array.from(document.querySelectorAll('tr')).forEach(e => {
        e.addEventListener('click', () => {
            stop();
        })
    });
    start();
    <div id="here">
      <table style='border: 1px solid black;'>
        <tr>
          <th>Key</th>
        </tr>
        <tr>
          <td>Foo</td>
        </tr>
        <tr>
          <td>Bar</td>
        </tr>
      </table>
    </div>
    Login or Signup to reply.
  1. You can give a variable name to setInterval function and make that variable global. Then, set an onclick event in your <td> which will clear the setInterval. For example:

    <script>
      $(document).ready(function () {
        var refresh = setInterval(function () {
          $("#here").load(window.location.href + " #here");
        }, 3000);
      });
    </script>
    
    <td onclick="clearInterval(refresh)"></td>
    

    Here, as name suggests, clearInterval function clears Interval which was gave it to.

    See more at W3Schools’ website.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search