Question

I have a AJAX function and setInterval function like this:

$("a[name=device_submit]").click(function(event) {
    var get_url = $(this).attr('href');
    event.preventDefault();

    $.ajax({
        url: get_url,
        success: function(data) {
            var data = JSON.parse(data);
            latitude = data[0].fields.latitude;
            longitude = data[0].fields.longitude;
            initialize(latitude, longitude)
        },

        statusCode: {
            400: function(data) {
                alert("No data found for this device!");
            }
        }
    });

    setInterval(function() {
        $.ajax({
            url: get_url,
            success: function(data) {
                var data = JSON.parse(data);
                latitude = data[0].fields.latitude;
                longitude = data[0].fields.longitude;

                //Remove current marker and change the position
                for (var i = 0; i < markersArray.length; i++) {
                    markersArray[i].setMap(null);
                }
                changeMarkerPosition(latitude, longitude);
            }
        });
    }, 9000);
});

When I click on first URL(let's say url1) everything is fine, the first AJAX request is sent, and another request is firef every 9 seconds.

Problem arises when I click url2. The success is beautifully responsed for url2 but now, the AJAX request is fired two times:

AJAXRequesturl1
AJAXRequesturl2

I don't want this, I want setInterval for only the url that has been clicked. That's it.

How to solve this one?

Était-ce utile?

La solution

The return value of setInterval is an Id allowing you to cancel that interval:

var timer = setInterval(...);

// later on...
clearInterval(timer)

You need to store the setInterval Id in a variable, and then clear the interval on the next mouse click.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top