Javascript delay function required

Hi, I am making an xmhhttp request, but it takes some time for the site to load, so I only get ReadyState = 3 and status = 200. So I need something that waits until readystate = 4, but I want to limit this function so that it only checks for one second if readistate = 4, otherwise do nothing.

What might such a delay function look like?

if (xmlhttp.readyState==4 && xmlhttp.status==200)//Add the delay here so that the else doesn't occur { var txt=xmlhttp.responseText; ..... else { document.write("status: " + xmlhttp.readyState + " " + xmlhttp.status); } 
+4
source share
4 answers

We can write a function to check the status of your xmlhttp object:

 var checkState = function(xmlhttp, callback) { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { callback(whatever, arguments, that, you, want, to, send); } else { // Check back again 1 sec later setTimeout(checkState, 1000); } }; 

Then you can use it as follows:

 checkState(xmlhttp, function(whatever, arguments, you, need) { // the code here will be run when the readyState is 4 and the status is 200 }); 

Two things:

  • The checkState function will return regardless of readyState, so make sure you only do what depends on it in the callback, not after.
  • If ReadyState and status never get your desired values, you're out of luck (but you can extend the function to accept a second callback that will time out).
0
source

Why did you invent the wheel?

You just have to pass the handler the XHRs onreadystatechange return message.

 xmlhttp.onreadystatechange = function() { switch( xmlhttp.readyState ) { case 4: { if (xmlhttp.status === 200) { var txt = xmlhttp.responseText; // or do something else here } break; } case 3: { // go interactive ! break; } } }; 
+4
source

A setInterval can do the trick if I understand you correctly:

 var seconds = 0; var interval = setInterval(function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Stop checking clearInterval(interval); // Ready var txt = xmlhttp.responseText; } else if (++seconds > 10) { // Do we give up? clearInterval(interval); // Give up } }, 1000); // Checks once every second 
+2
source

Maybe use something like

Edit: use onreadystatechange:

 Connection.onreadystatechange = function() { if (Connection.readyState != 4) { return; } else { // do your thing } }; 
-2
source

Source: https://habr.com/ru/post/1337965/


All Articles