简体   繁体   中英

Unexpected behavior with “SetInterval” in JavaScript

I have a JavaScript that makes request to a servlet. The request works but I can't get it to repeat at the specified time interval of 1 sec. What am I doing wrong?

I am quite new to front-end development and JavaScript.

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

setInterval works with the arguments setInterval(callbackFunction, timingInMilliseconds) .

It looks like you are putting your call to $.get directly in the callbackFunction argument. This unfortunately doesn't work as the result of your call to $.get is passed as the argument, not the function itself. Even if you did pass the function, it wouldn't be called with the proper arguments.

Instead wrap it in an anonymous function call or place it in a function, like so:

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

Or:

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

If you insisted on using $.get directly in setInterval , you could use something like:

 setInterval(function(a,b,c){

      console.log(a + b +c);  

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

In most browsers (see the link above) you can use setInterval with the call:

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

Anything you want to do, put inside of this block below:

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

Try it now with this:

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

在任何模糊事件上,您都会创建一个新的interval实例,它们会保留在内存中并可能引起冲突,创建一个全局interval ref对象并为其设置间隔引用,并在开始新的interval之前处置旧的interval。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM