user123
user123

Reputation: 79

How to stop the setInterval using jQuery

I have a dropdown where I can select the time for the setInterval.

test.php:

 <select id="proc_id" class="multiselect custom processselect" name="proc_id" style="display: none;">
    <option>Select</option>
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
 </select>

If select "0" stop the executing the setinterval and 1 for 1 sec and 2 for 2 sec.

test.js

var set_time = 0;
var interval;

$('#proc_id').change(function() {
    set_time = $('#proc_id :selected').val();
    // alert((set_time));
    if(parseInt(set_time) > 0) {
        set_time= set_time * 1000;
        interval = setInterval(function() {
            getFileProcessList(start_date);
            getResultInfoList(start_date); 
        }, set_time);
    } 
    else {
        alert('bye');
        clearInterval(interval);
    }
}); 

If I selected the 0, it not clearing the interval. Please can anyone help how to stop the setInterval function?

Upvotes: 0

Views: 68

Answers (1)

Trung Duong
Trung Duong

Reputation: 3475

You should clear the previous interval before start the new one. Your code should be updated like this

    var set_time = 0;
    var interval = 0;
    $('#proc_id').change(function(){
        set_time=$('#proc_id :selected').val();
        if(parseInt(set_time) > 0) {

            set_time= set_time * 1000;
            if (interval != 0) {
              // clear previous interval before start the new one
              clearInterval(interval);
            }
            interval = setInterval(function() {
                getFileProcessList(start_date);
                getResultInfoList(start_date);
            }, set_time);
        } 
        else {
            clearInterval(interval);
            interval = 0;
        }
    });  

I've created a sample at this link https://jsfiddle.net/mhL907eo/1/, please check.

Upvotes: 1

Related Questions