为什么ajax反复被调用了,setInterval每次都会触发两次Ajax调用

  • Post author:
  • Post category:其他


我有以下JS代码:

var delay = 5000;

function init() {

setInterval(getFileCount, delay);

}

function getFileCount() {

$.get(‘/notification/course-file-count’, function(response) {

if (response.items.length === 0) {

return false;

}

// Do stuff with response

});

}

在页面加载时,我正在调用init()函数。我们的想法是开始间隔并每隔5秒调用getFileCount()函数。

因此,在页面加载和运行后,间隔等待5秒,但总是使Ajax调用两次。

我错过了什么?

更新

我知道init()函数在页面加载时被触发两次(感谢Yury Tarabanko的评论)。我不太明白,为什么。几乎完整的代码:

$(function() {

‘use strict’;

function handleCourseNotification() {

var delay = 5000;

function init() {

setInterval(getFileCount, delay);

}

function getFileCount() {

$.get(‘/notification/course-file-count’, function(response) {

if (response.items.length === 0) {

return false;

}

updateCourseList(response.items);

});

}

function updateCourseList(items) {

// update course list…

}

return {

init: init

};

}

if ($(‘#js-auth-course-list’).length) {

var notificationHandler = handleCourseNotification();

notificationHandler.init();

}

});

这是一个小模块,我在页面加载后初始化,如果DOM中有特定元素 – $(‘#js-auth-course-list’)。为什么init实际上被调用了2次?我直接叫它一次。