Hi,

I have two jQuery functions. One does an AJAX request on a timer, and one does an AJAX request when a button is clicked. The problem I've encountered is that when the button is clicked, the timer is still running so the function gets called twice. I want to stop the timed function with clearInterval when the button is clicked, and re-start it (with setInterval) once the button function has finished. Is this possible? Below is a stripped down version of my code with comments which show where I want to stop and re-start the timed function. Thanks in advance for your assistance.

// Begin Javascript...

$(document).ready(function(){

    // Timed function
    $(function() {
        var intervalID = setInterval(myTimer, 5000);
        function myTimer() {
            $.ajax({
                type : 'POST',
                url : 'page.php',
                dataType : 'json',
                data: {
                    name : $('#name').val()
                },
                success : function(data) { // if AJAX successful
                    if (data.error === true) { // User data fail
                        alert('user error');
                    } else {
                        alert('ok');
                    }
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) { // if AJAX unsuccessful
                    alert('system error');
                }
            });
        }
    });

    // Manual function triggered by button click
    $('#button').click(function() {
        // clearInterval here!!!
        $.ajax({
            type : 'POST',
            url : 'page.php',
            dataType : 'json',
            data: {
                name : $('#name').val()
            },
            success : function(data) { // if AJAX successful
                if (data.error === true) { // User data fail
                    alert('user error');
                } else { // Success
                    // setInterval here so it re-starts
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) { // if AJAX unsuccessful
                alert('system error');
            }
        });
    });

});

EDIT 29/03/11 at 21:38:

I am now stopping and re-starting the timed function successfully, and I'm also triggering it from within the manual function that runs when the button's clicked. But, it seems as though somehow there are two instances of the function running in parallel, as it starts happening too quickly and sometimes runs twice at the same time (I know this as I check for this within the function. Here is the updated JS, can anyone see why this could be happening? As far as I can tell, I am always clearing the timed function before re-starting it.

$(document).ready(function(){

// Timed function
function getActivity() {
    // Check The timed function is already running
    var actvity_ajax_status = $('#activity_ajax_status').val();
    if (actvity_ajax_status == 'on') {
        // The timed function is already running, so do nothing
        return;
    }
    // If it wasn't running, we'll continue. Log that the timed function has started
    $('#activity_ajax_status').val('on').change();
    // AJAX
    $.ajax({
        type : 'POST',
        url : 'get-messages.php',
        dataType : 'json',
        data: {
            member_id : $('#member_id').val(),
            activity_id : $('.activity_id:first').val()
        },
        success : function(data) {
            if (data.error === true) {
            } else {
                // Do something
            }
            // log that the timed function has started
            $('#activity_ajax_status').val('off').change();
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

// Start Timed function and run it every 20 seconds
var intervalID = setInterval(function() { getActivity(); }, 20000);

// 'Button' function
$('#submit').click(function() {
    // Disable the submit button
    $(this).attr('disabled','disabled').animate({opacity: 0.25});
    // Stop the timed function
    clearInterval(intervalID);
    // Save Message
    $.ajax({
        type : 'POST',
        url : 'send-message.php',
        dataType : 'json',
        data: {
            message_to : $('#member_id_to').val(),
            message_content : $('#message_content').val()
        },
        success : function(data) {
            if (data.error === true) {
                var intervalID = setInterval(function() { getActivity(); }, 20000);
                $('#public_message_submit').removeAttr('disabled').animate({opacity: 1});
            } else {
                // Check if the timed function is running
                var actvity_ajax_status = $('#js_activity_ajax_status').val();
                if (actvity_ajax_status == 'on') {
                    // Wait for the timed function to finish running
                    $('#js_activity_ajax_status').change(function() {
                        // Start Timed function
                        var intervalID = setInterval(function() { getActivity(); }, 20000);
                        $('#public_message_content').val('');
                        $('#public_message_submit').removeAttr('disabled').animate({opacity: 1});
                    });
                } else { // The timed function is not runing
                    // Start Timed function
                    var intervalID = setInterval(function() { getActivity(); }, 20000);
                    $('#public_message_content').val('');
                    $('#public_message_submit').removeAttr('disabled').animate({opacity: 1});
                }
            }
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
});

});

2 answers

danwellman 5600
0
points
This was chosen as the best answer

The timer function doesn't need to be in a $(function() { }), this is just a short hand way of doing $(document).ready(function() { }) which you are already doing...

Also, it is now considered best practice to use an anonymous calling function as the first argument in setInterval and setTimeout

Try this:

// Begin Javascript...

$(document).ready(function(){

    // Timed function
   function myTimer() {
        $.ajax({
            type : 'POST',
            url : 'page.php',
            dataType : 'json',
            data: {
                name : $('#name').val()
            },
            success : function(data) { // if AJAX successful
                if (data.error === true) { // User data fail
                    alert('user error');
                } else {
                    alert('ok');
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) { // if AJAX unsuccessful
                alert('system error');
            }
        });
    }
    var intervalID = setInterval(function() { myTimer(); }, 5000);

    // Manual function triggered by button click
    $('#button').click(function() {
        clearInterval(intervalID);
        $.ajax({
            type : 'POST',
            url : 'page.php',
            dataType : 'json',
            data: {
                name : $('#name').val()
            },
            success : function(data) { // if AJAX successful
                if (data.error === true) { // User data fail
                    alert('user error');
                } else { // Success
                    // setInterval here so it re-starts
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) { // if AJAX unsuccessful
                alert('system error');
            }
        });
    });

});
Answered about 8 years ago by danwellman
0
points

Question edited on 29/03/11 at 21:38 with new issue, as function seems to be running two parallel instances.

Answered almost 8 years ago by Edward Williams
  • I'll look it over, but it may be more helpful to post a new question and then link back to this one so people have context. It might get you more responses, and it will also allow you to mark the correct answer for the new problem without loosing the solution to the old one. Ktash almost 8 years ago