As part of a Javascript project I'm working on, there are some synchronous ajax calls (I guess that makes it "sjax", but I digress). I'm now writing a debugging panel which would allow me to test out the site with some artificially simulated network conditions by wrapping $.ajax
. Simple things: faking a 500 response etc, and making the ajax calls take much longer.
For the asynchronous calls, it's simple. When the real response comes back, add a setTimeout
to make it wait for the artificial response time before triggering the callback. However, this doesn't work with the synchronous calls obviously, since setTimeout
isn't synchronous.
So, is there a way to make a Javascript program perform a blocking wait for a set amount of time?
The only thing I could think of would be something like this:
function wait(ms) {
var start = +(new Date());
while (new Date() - start < ms);
}
Is there a better solution?
(Also, please assume there's a good reason for the blocking ajax calls... :-\
)
import { setTimeout } from "timers/promises"; const yourFunction = async () => { await setTimeout(5000); console. log("Waited 5s"); await setTimeout(5000); console.
Many programming languages have a sleep function that will delay a program's execution for a given number of seconds. However, this functionality is absent from JavaScript due to its asynchronous nature.
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
Do not do it on the JavaScript level. Get a proxy such as Fiddler and set up an AutoResponder to delay the call by a time period.
If it's just for debugging purposes to have an artificial delay:
alert('block me one more time');
There is no reasonable other approach to have a blocking code in ECMAscript. Since Javascript is executed in the same thread ("UI thread") which browsers use to render the DOM and to certain other things, the whole show was designed not to block anything.
Of course you can fake it by using a loop, but its a perversion of the show.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With