2017-12-03 283 views
1

我有一個向servlet發出請求的JavaScript。請求有效,但我不能讓它在1秒的指定時間間隔重複。我究竟做錯了什麼?JavaScript中的「SetInterval」意外的行爲

我對前端開發和JavaScript很新穎。你想要做

$(document).ready(function() { 
     $('#userName').blur(function(event) { 
       var name = $('#userName').val(); 
       setInterval($.get('JqueryServlet', { 
         userName : name 
       }, function(responseText) { 
         $('#ajaxResponse').text(responseText);}), 1000); 
     }); 
}); 
+2

[setInterval回調函數只能運行一次](https://stackoverflow.com/questions/10182714/setinterval-callback-only-runs-once) – Xufox

回答

1

什麼,就把下面這個區塊內:

setInterval(function(){ 
    alert("I will be called in 3 second and again after 3 seconds"); 
}, 3000); 

這個現在就來試試:

$(document).ready(function() { 
    $('#userName').blur(function(event) { 
      var name = $('#userName').val(); 
      setInterval(function(){ 
       $.get('JqueryServlet', { 
        userName : name 
       }, function(responseText) { 
        $('#ajaxResponse').text(responseText); 
       }); 
      }, 1000); 
    }); 
}); 
2

setInterval工作with the argumentssetInterval(callbackFunction, timingInMilliseconds)

它看起來像你打電話給$.get直接在callbackFunction的論點。由於您致電$.get的結果是作爲參數傳遞的,而不是函數本身,所以很遺憾,這不起作用。即使你傳遞了函數,它也不會被正確的參數調用。

而是將它包裝在一個匿名函數調用或將其放置在一個函數,像這樣:

function getServlet() { 
    // code 
} 
setInterval(getServlet, 1000); // to go off every 1 second 

或者:

setInterval(function() { 
    // code 
}, 1000); 

如果直接在setInterval使用$.get堅持,你可以使用類似於:

setInterval(function(a,b,c){ 

     console.log(a + b +c); 

    }, 500, "a", "b", "c"); 

在大多數瀏覽器中(請參見第Ë上面的鏈接),你可以使用setInterval與呼叫:

setInteval(callbackFunction, timingInMilliSeconds, callbackArg, callbackArg, ...); 
1

上的任何模糊情況下,您創建的間隔新實例,它們保留在內存中,並可能導致衝突,建立一個全球性的間隔裁判對象,並設置間隔參考它和之前開始新的時間間隔配置舊時間間隔。