PHP dev
PHP dev

Reputation: 420

Need to get refresh a page every X seconds based on the select box value in jquery

Code:

<script>
   var interval =0;
   var auto_refresh= 0;
   $(document).ready(function() {
       alert("hi");
       $('#reload_interval').change(function() {
           var reload   = $(this).val();
           interval = reload * 1000;
           if(reload !='') {
               auto_refresh = setInterval(function() {
                   alert(interval);
                   console.log(interval);               
               }, interval);
           }else {
               clearInterval ( auto_refresh );
           }
       });
   });
</script>
<select id="reload_interval" name="reload_interval">
    <option value="">Reload Interval</option>
    <option value="30">30 Secs</option>
    <option value="45">45 Secs</option>
    <option value="60">60 Secs</option>
</select>

At first time,all are working good.After that If i select 60secs or 45 secs it loads before reaches the 45 secs or 60secs....

Where goes wrong?

Upvotes: 2

Views: 273

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to clear the previous interval before setting a new one

var interval = 0;
var auto_refresh = 0;
$(document).ready(function() {
  $('#reload_interval').change(function() {
    var reload = $(this).val();
    interval = reload * 1000;
    if (auto_refresh) {
      clearInterval(auto_refresh); //clear the previous interval before setting a new one
    }
    if (reload) {
      auto_refresh = setInterval(function() {
        snippet.log(interval);
      }, interval);
    }

  });
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="reload_interval">
  <option></option>
  <option>1</option>
  <option>2</option>
  <option>4</option>
  <option>6</option>
</select>

In your code when you select the second value, the previous interval is still running, so you will have 2 intervals executing after 2nd change of the value, same way 3 intervals after 3rd change of value.

Upvotes: 2

Related Questions