Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safety in Javascript?

I have a function called save(), this function gathers up all the inputs on the page, and performs an AJAX call to the server to save the state of the user's work.

save() is currently called when a user clicks the save button, or performs some other action which requires us to have the most current state on the server (generate a document from the page for example).

I am adding in the ability to auto save the user's work every so often. First I would like to prevent an AutoSave and a User generated save from running at the same time. So we have the following code (I am cutting most of the code and this is not a 1:1 but should be enough to get the idea across):

var isSaving=false; var timeoutId; var timeoutInterval=300000; function save(showMsg) {   //Don't save if we are already saving.   if (isSaving)   {       return;   }   isSaving=true;   //disables the autoSave timer so if we are saving via some other method   //we won't kick off the timer.   disableAutoSave();    if (showMsg) { //show a saving popup}   params=CollectParams();   PerformCallBack(params,endSave,endSaveError);  } function endSave() {       isSaving=false;     //hides popup if it's visible      //Turns auto saving back on so we save x milliseconds after the last save.     enableAutoSave();  }  function endSaveError() {    alert("Ooops");    endSave(); } function enableAutoSave() {     timeoutId=setTimeOut(function(){save(false);},timeoutInterval); } function disableAutoSave() {     cancelTimeOut(timeoutId); } 

My question is if this code is safe? Do the major browsers allow only a single thread to execute at a time?

One thought I had is it would be worse for the user to click save and get no response because we are autosaving (And I know how to modify the code to handle this). Anyone see any other issues here?

like image 665
JoshBerke Avatar asked Feb 12 '10 17:02

JoshBerke


People also ask

What is meant by thread safety?

Thread safety is the avoidance of data races—situations in which data are set to either correct or incorrect values, depending upon the order in which multiple threads access and modify the data. When no sharing is intended, give each thread a private copy of the data.

What is thread safety example?

5) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String, etc. 6) Atomic operations in Java are thread-safe like reading a 32-bit int from memory because it's an atomic operation it can't interleave with other threads.

How do you ensure a code is thread safe?

Using Atomic Variable Using an atomic variable is another way to achieve thread-safety in java. When variables are shared by multiple threads, the atomic variable ensures that threads don't crash into each other.

Is node thread safe?

2 Answers. Show activity on this post. All are thread safe. There are no threads, JavaScript is single threaded, it's impossible for two javascript statements to run at the same time.


2 Answers

JavaScript in browsers is single threaded. You will only ever be in one function at any point in time. Functions will complete before the next one is entered. You can count on this behavior, so if you are in your save() function, you will never enter it again until the current one has finished.

Where this sometimes gets confusing (and yet remains true) is when you have asynchronous server requests (or setTimeouts or setIntervals), because then it feels like your functions are being interleaved. They're not.

In your case, while two save() calls will not overlap each other, your auto-save and user save could occur back-to-back.

If you just want a save to happen at least every x seconds, you can do a setInterval on your save function and forget about it. I don't see a need for the isSaving flag.

I think your code could be simplified a lot:

var intervalTime = 300000; var intervalId = setInterval("save('my message')", intervalTime); function save(showMsg) {   if (showMsg) { //show a saving popup}   params=CollectParams();   PerformCallBack(params, endSave, endSaveError);    // You could even reset your interval now that you know we just saved.   // Of course, you'll need to know it was a successful save.   // Doing this will prevent the user clicking save only to have another   // save bump them in the face right away because an interval comes up.   clearInterval(intervalId);   intervalId = setInterval("save('my message')", intervalTime); }  function endSave() {     // no need for this method     alert("I'm done saving!"); }  function endSaveError() {    alert("Ooops");    endSave(); } 
like image 102
Jonathon Faust Avatar answered Sep 27 '22 15:09

Jonathon Faust


All major browsers only support one javascript thread (unless you use web workers) on a page.

XHR requests can be asynchronous, though. But as long as you disable the ability to save until the current request to save returns, everything should work out just fine.

My only suggestion, is to make sure you indicate to the user somehow when an autosave occurs (disable the save button, etc).

like image 42
mikefrey Avatar answered Sep 27 '22 16:09

mikefrey