Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking Synchronous AJAX

Is there a way to perform a synchronous AJAX query that doesn't freeze the browser? In my opinion synchronous requests are a lot easier to work with in most cases, but the fact that they block other parts of the code from executing is a real killer. Is there a way to get synchronous AJAX without the negative side effects? (And yes, I realize that the term "Synchronous AJAX" is an oxymoron.)

like image 564
Ajedi32 Avatar asked Dec 15 '22 08:12

Ajedi32


1 Answers

I'll provide an example of the bad side of effects of allowing such behavior.

Lets say you have this program:

<script>
var file = "foo.json";

function nullIt() {
    file = null;
}

function loadFile() {
    if (file != null) {
        synchronousLoad(file);//imagine the load takes 5 seconds
        alert("i just loaded: " + file);
    }
}

window.onload = loadFile;
</script>
<button onclick="nullIt()">click me</button>

The bad thing here-

  • while the synchronousLoad() is blocking for 5 seconds, the user clicks the button, and the event handler quickly runs to completion.
  • Now the file variable is null.
  • synchronousLoad() finishes and returns, letting execution resume on the next line of code
  • but file is now null, and the message output to the user is broken.

The real issue here you cannot reason about your code the same way anymore. Just because some fact was true on line 5, doesnt mean its still true on the very next line. This makes it very difficult to write an error free program.

Some programming languages support multithreading, and you have to deal with these issues, although you have tools to help deal with these problems. But, it's still a lot of extra effort on the programmers part.

Comparatively speaking, using callbacks to do asynchronous operations is ez-mode.

like image 113
goat Avatar answered Dec 17 '22 22:12

goat