javascript AJAX 错误函数未正确清除间隔

czfnxgou  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(91)

当页面加载时,我每隔30秒就发出一个 AJAX 请求来加载一个json文件:

jQuery(document).ready(function () {
    loadBuildInterval = setInterval(loadBuildData, intervalTime); //Start interval when document is loaded
});

function loadBuildData() {
    jQuery.ajax({
        url: fileUrl + '?v' + (Math.round(new Date()/1000)), //Add unique version to json file every time it is requested (cache busting).
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function (result) {
                clearInterval(loadBuildInterval); //Reload interval with new duration
                loadBuildInterval = setInterval(loadBuildData, intervalTime);
        },
        error: function () {
            clearInterval(loadBuildInterval);
            console.log('Reload Changes - Aborting - ajax error.');
        }
    });
}

当它到达error函数时,它开始以浏览器所能达到的最快速度发出 AJAX 请求,而不是清除间隔。

roejwanj

roejwanj1#

我建议使用setTimeout而不是setInterval,试试这个:

jQuery(document).ready(function () {
    loadBuildData();
});

function loadBuildData() {
    jQuery.ajax({
        url: fileUrl + '?v' + (Math.round(new Date()/1000)), //Add unique version to json file every time it is requested (cache busting).
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function (result) {
            if (result !== null) { //If the json file is not empty, continue
                if (userActiveBuild === 'loading') { //Set initial active build. This will be the build the user loaded into
                    userActiveBuild = result['currentBuild'];
                }
                dataLoaded(result); //Start comparing build
                setTimeout(function () {
                    if (result['inScript'] !== '0') { //If a script must be loaded, run function for it
                        inScript(result);
                    }
                    if (result['inStyle'] !== '0') { //If a style must be loaded, run function for it
                        inStyle(result);
                    }else{
                        jQuery("link[href*='"+scriptURL+"css/inStyle.css']").remove();
                    }
                }, inScriptPause);

                if (intervalTime !== result['userTestInterval']) { //Update interval to the one set in the wp settings
                    // Change interval
                    intervalTime = result['userTestInterval'];
                }
            }else{
                //No json data.
            }
            // Recall the function after intervalTime
            setTimeout(loadBuildData, intervalTime); 
        },
        error: function () {
            console.log('Reload Changes - Aborting - ajax error.');
        }
    });
}

相关问题