Problem with several Javascript timers

0

I'm trying to create a website that contains a section with many timers to measure the time it takes for certain tasks. The problem I have when I interact with two timers at the same time, when you have several counters working and you try to stop the first stop for the last one and the rest keeps running. My code:

HTML:

<div id="taskModal2" class="col-lg-6">
    <span id="title-Addsubtask">SUBTAREAS (0)</span>
    <div class="subtaskList">
        <i class="si si-bell alertSubtask"></i>
        <input type="checkbox" id="subtaskCheck" name="subtaskCheck" />
        <div class="subtaskTitle">Titulo de la subtarea</div>
        <div><i class="fa fa-play"><span class="subtaskTime">00:00:00</span></i></div>
    </div>
    <div class="subtaskList">
        <input type="checkbox" id="subtaskCheck" name="subtaskCheck" />
        <div class="subtaskTitle">Titulo de la subtarea</div>
        <div><i class="fa fa-play"><span class="subtaskTime">00:00:00</span></i></div>
    </div>
    <div>
        <textarea type="text" id="inputSubtask" name="inputSubtask" Placeholder="Nueva subtarea"></textarea>
        <div class="mask">
            <div class="buscador">
                <input type="search" class="rectangle-4">
                <i class="si si-magnifier searchIcon"></i>
            </div>
            <div class="client-list">
            </div>
            <div class="optionSubmenuOpenTask">
                <span>Cancel</span>
            </div>
        </div>
    </div>
</div>

Javascript:

// Change Start To Pause
$(document).on('click', '.fa-play', function(){

    var id = $(this).parent().attr('id');

    $(this).removeClass('fa-play');
    $(this).addClass('fa-pause');
    var aux = $(this);

    var horas = $(this).children('.subtaskTime').html().split(':');

    $.ajax({
        url: base_url + 'Task/startSubtaskTimer',
        type: "post",
        data:{
            'subtaskId' : aux.siblings("#subtaskCheck").data('subtaskid'),
            'employeeId' : $('#employeeId').val()
        },
        success:function(){
        },
        error:function(){
        }
    });

    var h = horas[0];
    var m = horas[1];
    var s = horas[2];
    var ht = '';
    var mt = '';
    var st = '';

    cont = setInterval(function(){
            s++;

            if(s == 60)
            {
                s = 00;
                m++;
            }

            if(m == 60)
            {
                m = 00;
                h++;
            }

            ht = '';
            mt = '';
            st = '';

            if(h < 10)
            {
                if(h == 00)
                {
                }else{
                    ht+='0';
                }
            }
            if(m < 10)
            {
                if(m == 00)
                {
                }else{
                    mt+='0';
                }
            }
            if(s < 10){
                st+='0';
            }

            ht+=h;
            mt+=m;
            st+=s;

            aux.children('.subtaskTime').html(ht + ":" + mt + ":" + st);
        }, 1000);
});

// Change Pause To Start
$(document).on('click', '.fa-pause', function(){

    var aux = $(this);
    $(this).removeClass('fa-pause');
    $(this).addClass('fa-play');

    $.ajax({
        url: base_url + 'Task/stopSubtaskTimer',
        type: "post",
        data: {
            'subtaskId'  : aux.siblings("#subtaskCheck").data('subtaskid'),
            'employeeId' : $('#employeeId').val(),
            'time'       : aux.children('.subtaskTime').html()
        }
    });

    clearInterval(cont);
});

PHP:

public function startSubtaskTimer(){

    date_default_timezone_set('Europe/Madrid');
    $subtaskId  = $_POST['subtaskId'];
    $employeeId = $_POST['employeeId'];

    $statement = "SELECT * FROM be_task_subtask_time WHERE subtaskId = '$subtaskId' && employeeId = '$employeeId'";

    $query = $this->db->query($statement);

    if($query->num_rows() > 0)
    {
        $data = array(
            'state' => '1'
        );

        $this->db->where('subtaskId', $subtaskId);
        $this->db->where('employeeId', $employeeId);
        $this->db->update('be_task_subtask_time', $data);

    }else{

        $data = array(
            'subtaskId'     => $subtaskId,
            'employeeId'    => $employeeId,
            'state'         => '1',
            'time'          => '00:00:00',
        );

        $this->db->insert('be_task_subtask_time', $data);
    }

}

public function stopSubtaskTimer(){

    date_default_timezone_set('Europe/Madrid');
    $subtaskId  = $_POST['subtaskId'];
    $employeeId = $_POST['employeeId'];
    $time       = $_POST['time'];

    $data = array(
        'state' => '0',
        'time'  => $time,
    );

    $this->db->where('subtaskId', $subtaskId);
    $this->db->where('employeeId', $employeeId);
    $this->db->update('be_task_subtask_time', $data);

}

Any idea where the problem comes from?

    
asked by Korzan 17.08.2017 в 11:24
source

1 answer

2

You are not correctly storing the process ids returned by setInterval , by what only remains stored in cont the last assignment.

As a solution you can assign this value to a property of the DOM element that receives the click events of the mouse.

In the code I used $(this).get(0).cont = setInterval(... to access through $jQuery.get() to the DOM element and there store in property cont return value.

During the break I access the stored value again to stop the planned interval with clearInterval($(this).get(0).cont); .

Here is a functional example (click on both timers and try it yourself):

// Change Start To Pause
base_url = '';
$(document).on('click', '.fa-play', function(){
    var id = $(this).parent().attr('id');
    $(this).removeClass('fa-play');
    $(this).addClass('fa-pause');
    var aux = $(this);

    var horas = $(this).children('.subtaskTime').html().split(':');

    $.ajax({
        url: base_url + 'Task/startSubtaskTimer',
        type: "post",
        data:{
            'subtaskId' : aux.siblings("#subtaskCheck").data('subtaskid'),
            'employeeId' : $('#employeeId').val()
        },
        success:function(){
        },
        error:function(){
        }
    });

    var h = horas[0];
    var m = horas[1];
    var s = horas[2];
    var ht = '';
    var mt = '';
    var st = '';

    $(this).get(0).cont = setInterval(function(){
            s++;

            if(s == 60)
            {
                s = 00;
                m++;
            }

            if(m == 60)
            {
                m = 00;
                h++;
            }

            ht = '';
            mt = '';
            st = '';

            if(h < 10)
            {
                if(h == 00)
                {
                }else{
                    ht+='0';
                }
            }
            if(m < 10)
            {
                if(m == 00)
                {
                }else{
                    mt+='0';
                }
            }
            if(s < 10){
                st+='0';
            }

            ht+=h;
            mt+=m;
            st+=s;

            aux.children('.subtaskTime').html(ht + ":" + mt + ":" + st);
        }, 1000);
});

// Change Pause To Start
$(document).on('click', '.fa-pause', function(){
    var aux = $(this);
    $(this).removeClass('fa-pause');
    $(this).addClass('fa-play');

    $.ajax({
        url: base_url + 'Task/stopSubtaskTimer',
        type: "post",
        data: {
            'subtaskId'  : aux.siblings("#subtaskCheck").data('subtaskid'),
            'employeeId' : $('#employeeId').val(),
            'time'       : aux.children('.subtaskTime').html()
        }
    });

    clearInterval($(this).get(0).cont);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="taskModal2" class="col-lg-6">
    <span id="title-Addsubtask">SUBTAREAS (0)</span>
    <div class="subtaskList">
        <i class="si si-bell alertSubtask"></i>
        <input type="checkbox" id="subtaskCheck" name="subtaskCheck" />
        <div class="subtaskTitle">Titulo de la subtarea</div>
        <div><i class="fa fa-play"><span class="subtaskTime">00:00:00</span></i></div>
    </div>
    <div class="subtaskList">
        <input type="checkbox" id="subtaskCheck" name="subtaskCheck" />
        <div class="subtaskTitle">Titulo de la subtarea</div>
        <div><i class="fa fa-play"><span class="subtaskTime">00:00:00</span></i></div>
    </div>
    <div>
        <textarea type="text" id="inputSubtask" name="inputSubtask" Placeholder="Nueva subtarea"></textarea>
        <div class="mask">
            <div class="buscador">
                <input type="search" class="rectangle-4">
                <i class="si si-magnifier searchIcon"></i>
            </div>
            <div class="client-list">
            </div>
            <div class="optionSubmenuOpenTask">
                <span>Cancel</span>
            </div>
        </div>
    </div>
</div>
    
answered by 17.08.2017 / 12:48
source