Home >Web Front-end >JS Tutorial >Simple JavaScript mutex lock sharing_javascript skills
Last year there were several projects that required the use of JavaScript mutex locks, so I wrote several similar ones. This is one of them:
!function ($) {
window.indream = window.indream || {};
$.indream = indream;
indream.async = {
) .push(action);
//If the lock is not used, the current action blocks the lock
if (!$.indream.async.lockStatus[lock] && action) {
$.indream .async.lockStatus[lock] = true;
if (arguments.length > 2) {
var args = 'arguments[2]';
for (var i = 3; i < arguments .length; i ) {
args = ', arguments[' i ']';
args ')');
},
/lock: Lock number
Then execute the waiting queue, otherwise unlock
if ($ .indream.async.waitings [lock] .Length) {
$ .indream.async.waitings [lock] [0] ();
} else {
🎜> lockStatus: [ ],
//
(lock, action) {
$.indream.async.waitings[code] = $.indream.async.waitings[code] || [];
$.indream.async.waitings[code].push (action);
},
//
: {
//Listen
//
listen: function (actionName , callback) {
var list = $.indream.async.action.callback.list;
list[actionName] = list[actionName] || [];
.push(callback );
},
args) {
var list = $.indream.async.action.callback .list;
if (list[actionName] && list[actionName].length) {
for (var i in list[actionName]) {
indream.async.action.call(list[ actionName][i], args);
//Existing callback list
//
list: []
},
🎜> if (arguments.length > 1) {
var args = 'arguments[1]';
for (var i = 2; i < arguments.length; i ) {
args = ', arguments[' i ']';
action(); > }
}
}
}(window.jQuery);
The elements of a mutex are:
•Lock and unlock
•Waiting queue
•Execution method
Usage of the above lock:
Copy code
The code is as follows:
var lock = 'scrollTop()';
Copy code
The code is as follows:
while(true) {//do something ...