1

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);
        });
});
halfer
  • 19,824
  • 17
  • 99
  • 186
nikk
  • 2,627
  • 5
  • 30
  • 51
  • 2
    Possible duplicate of [setInterval callback only runs once](https://stackoverflow.com/questions/10182714/setinterval-callback-only-runs-once) – Sebastian Simon Dec 03 '17 at 01:37

3 Answers3

2

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, ...);
not-inept
  • 104
  • 2
1

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);
    });
});
slon
  • 1,002
  • 1
  • 8
  • 12
1

on any blur event you create new instance of interval and they remain in memory and can cause conflict ,create a global interval ref object and set interval reference to it and before start new interval dispose old interval.

Hossein Oraee
  • 229
  • 1
  • 5