Anonymous javascript polling function does not trigger setTimeout ajax call immediately -


this question has answer here:

i have anonymous polling function has settimeout kick off ajax call every 30 seconds. however, anonymous function kick off reason ajax call not kick off immediately, starts after 30 seconds. missing calling trigger right away?

(function poll() {         console.log('polling called');         settimeout(function () {             $.ajax({                 url: "/server/call",                 type: 'get',                 datatype: "json",                  timeout: 30000,                 success: function (data) {                     var currentdate = new date();                     var datetime = "last sync: " +                  currentdate.getdate() + "/" + (currentdate.getmonth() + 1) + "/"                     + currentdate.getfullyear() + " @ "                     + currentdate.gethours() + ":"                     + currentdate.getminutes() + ":"                     + currentdate.getseconds();                      console.log(datetime);                     console.log('call successful at: ' + datetime);                 }             });         },         30000);     })(); 

the logging starts off after 30 seconds , not right away. thanks

that not remotely settimeout() does. settimeout() calls function, once, , after given time has expired.

setinterval() close want, calls function first time after interval has expired once.

what need this:

const everythree = () =>              $.ajax({                 url: "/server/call",                 type: 'get', ... everythree(); setinterval(everythree, 3000); 

if don't using setinterval(), can same thing manually:

const everythree = () => {             settimeout(everythree, 3000);              $.ajax({                 url: "/server/call",                 type: 'get', ... everythree(); 

if suspect ajax call might run long, following:

const everythree = () =>              $.ajax({                 url: "/server/call",                 type: 'get',            ...            })            .always(() => settimeout(everythree, 3000));   everythree(); 

this make next ajax call 3 seconds after previous 1 has succeeded, failed, or timed-out.

edit:

if don't have const or => ("fat-arrow") in environment, choices are

  1. make var , function. inferior in many ways, universally available.
  2. use transpiler babel , advantages of modern language (constants, easy anonymous functions, deconstruction, array-spreading), @ cost of slight increase in complexity in operational environment.

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -