处理多个Ajax请求:ClearTimeout

时间:2014-11-07 14:59:24

标签: javascript ajax

我有来自MySQL请求的元素 它们都有唯一的id,也作为参数插入到onclick调用函数中。

每次点击都会导致将数据搜索到数据库中。这样做直到数据库发送预期答案。当预期答案到来时,功能需要停止。

我不知道如何知道,当预期数据到达时,如何停止此功能 我无法将var x设置为其他值var x is not defined

function search(id) {
 document.getElementById(id).style.color = "red";
 var x = setInterval(function () {answer(id)}, 1000);
}

function answer(id) {
document.getElementById("result").innerHTML = id;
    /*
    AJAX request, looks for an anwser
    
     if(answer)
     {
     clearTimeout(x); // var x is not defined
     }
      
    */
}
<div id="one" onclick="search('one');">
    click
</div>

<div id="two" onclick="search('two');">
    click
</div>

<div id="result">
    
</div>

2 个答案:

答案 0 :(得分:0)

创建间隔对象

var intervals = {};
function search(id) {
    document.getElementById(id).style.color = "red";
    intervals[id] = setInterval(function () {answer(id)}, 1000);
}

function answer(id) {
    document.getElementById("result").innerHTML = id;
    /*
    AJAX request, looks for an anwser

     if(isAnswered)
     {
         clearTimeout(intervals[id]);
     }

    */
}

更好的是使用setTimeout而不用担心间隔

function search(id) {
    document.getElementById(id).style.color = "red";
    answer(id);
}

function answer(id) {
    document.getElementById("result").innerHTML = id;
    /*
    AJAX request, looks for an anwser

     if(!isAnswered)
     {
         window.setTimeout( function () { answer(id); }, 1000);
     }

    */
}

答案 1 :(得分:-1)

你在函数中声明了X,你无法在外面访问它..

尝试这样的事情:

var x; // here you will have a global variable
function search(id) {
     document.getElementById(id).style.color = "red";
     return setInterval(function () {answer(id)}, 1000); // return the timeinterval ID
}

function answer(id) {
    document.getElementById("result").innerHTML = id;
    clearTimeout(x);
    /*
    AJAX request, looks for an anwser
    
     if(answer)
     {
     clearTimeout(x); // var x is not defined
     }
      
    */
}
<div id="one" onclick="x = search('one');"> <!-- set X = the interval -->
    click
</div>

<div id="two" onclick="x = search('two');">
    click
</div>

<div id="result">
    
</div>