JavaScript中“SetInterval”的意外行为

时间:2017-12-03 01:33:26

标签: javascript jquery ajax jsp servlets

我有一个向servlet发出请求的JavaScript。请求有效,但我不能让它以1秒的指定时间间隔重复。我究竟做错了什么?

我对前端开发和JavaScript都很陌生。

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

3 个答案:

答案 0 :(得分:2)

setInterval有效with the arguments setInterval(callbackFunction, timingInMilliseconds)

您似乎直接在$.get参数中调用了callbackFunction。遗憾的是,由于您对$.get的调用是作为参数传递而不是函数本身,因此不起作用。即使您确实传递了该函数,也不会使用正确的参数调用它。

而是将其包装在匿名函数调用中或将其放在函数中,如下所示:

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

或者:

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

如果您坚持在$.get中直接使用setInterval,则可以使用以下内容:

 setInterval(function(a,b,c){

      console.log(a + b +c);  

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

在大多数浏览器中(请参阅上面的链接),您可以通过以下呼叫使用setInterval

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

答案 1 :(得分: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 :(得分:1)

在任何模糊事件上创建新的间隔实例,它们会保留在内存中并导致冲突,创建全局间隔引用对象并设置间隔引用,并在开始新间隔之前配置旧间隔。