0

function ajax1(a, b, c){ 
  c = new XMLHttpRequest;
  c.open('GET', a);
  c.onload = b;
  c.send()
}

function handleData1(uu){
  console.log(10)
}
for (var i=0;i<5;i++){
setTimeout(ajax1("some_url", function(e){handleData1(this.response) }),1000)
}

I am stuck,I can't use the setInterval function with ajax.

this if a simplified version of what I want my code to do.

As said in the code,I tried using setTimeout too but it didn't work,javascript just ignores the funcion setInterval or setTimeout.

Newdude
  • 25
  • 7
  • 2
    The first argument of `setInterval` needs to be a function. Here you are sending `undefined` (which is the returned value of the `ajax1` function) – Seblor Nov 22 '20 at 00:48
  • Does this answer your question? [Pass parameters in setInterval function](https://stackoverflow.com/questions/457826/pass-parameters-in-setinterval-function) – Ivar Nov 22 '20 at 00:50
  • Are you sure you want to put a `setInterval` in a loop? Right now it will be called 5 times every second. – Ivar Nov 22 '20 at 00:51
  • I changed the old function setinterval with setimeout – Newdude Nov 22 '20 at 01:27
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+setTimeout+in+for+loop) of [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/q/3583724/4642212) and the one Ivar linked. – Sebastian Simon Nov 22 '20 at 02:36

1 Answers1

2

setInterval requires the first parameter to be a function.

for (var i=0;i<5;i++){
   setInterval(function(){
      ajax1("some_url", function(e){
         handleData1(this.response) 
      });
   }, 1000);
}
Liftoff
  • 24,717
  • 13
  • 66
  • 119
  • this works with setTimeout but this works just for the first time, i want to print "10" once a second ,with this code i have to wait for 1 second just for the first console.log, then it stops working, this is more noticeable if you put something like 5000 instead of 1000 – Newdude Nov 22 '20 at 01:27