Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking "wait" function in javascript?

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... :-\)

like image 760
nickf Avatar asked Nov 09 '11 15:11

nickf


People also ask

How do you sleep 5 seconds in JavaScript?

import { setTimeout } from "timers/promises"; const yourFunction = async () => { await setTimeout(5000); console. log("Waited 5s"); await setTimeout(5000); console.

Is there a wait function in JavaScript?

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.

How do you wait 1 second in JavaScript?

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.


2 Answers

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.

like image 148
epascarello Avatar answered Oct 16 '22 23:10

epascarello


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.

like image 27
jAndy Avatar answered Oct 16 '22 23:10

jAndy