Ajax延迟请求为什么会调用两个数据?

我有个很奇怪的问题......

我在第一次调用后就一直调用Ajax,第一次是下拉选择,另一次是连续的延迟。第一次调用是在从下拉列表中选择一个city之后,我将该值存储在一个全局变量中:

$('.selectCity').change(function () {
    var city = $(this).val();
    ...
    ...

然后在Ajax调用中使用该city,如下所示:

var timer, delay = 3000;

timer = setInterval(function(){
    $.ajax({
    type: 'GET',
    url: '/riders/location/track',
    data: {
       'city': city
    },
    ...
    ...
    ...

当我选择一个city时,假设是london,那么延迟Ajax请求调用并得到预期的结果;但是当我再次选择另一个city时,比如Boston,那么延迟方法会调用两次——一次是对london,另一次才是对Boston,不应该只调用Boston吗?

Your problem is that you are defining an interval for each city change, but not clearing it after the city is changed, so you got an accumulated intervals.

setInterval(callback, ms)

Schedules callback to be called repeatedly every ms milliseconds. Any additional arguments are passed straight through to the callback.

If you want only to delay the Ajax request once, you should use setTimeout api instead.

You should clear the setInterval handler before you call it again. More information is here https://www.w3schools.com/jsref/met_win_clearinterval.asp

In your case it is

var timer, delay = 3000;

// Clear out the previous timer.
// This will start a new timer again.
clearInterval(timer);

timer = setInterval(function(){
    $.ajax({
    type: 'GET',
    url: '/riders/location/track',
    data: {
       'city': city
    },
    ...
    ...
    ...