If you have this knowledge, you will think that this is meaningless because script scripts will never produce concurrency. It is true that script execution is a single thread. Even if there are setTimeout, setInterval, and other methods, it will never produce concurrency. So here is just a simulation.
Describe the application scenario. The online examination system provides automatic and manual assignments. The structure is roughly as follows:
Function handInAuto (){
DoHandIn ();
}
Function handInMan (){
DoHandIn ();
}
Function doHandIn (){
...
}
We can usually cancel the timer clock in the doHandIn method and shield the manual buttons so that doHandIn will not be executed repeatedly. You can also disable the manual button in handInAuto to cancel the clock in handInMan.
However, the overall feeling is not perfect, and the submit logic is mixed with the control logic. Isn't it like java? You can declare it with a keyword.
Public synchronized void doHandIn (){
...
}
Finally, the code block is added with a jsynchronized ("handIn") Judgment statement. Each call is locked for a certain period of time, so that the call is not executed continuously.
Function doHandIn (){
If (jsynchronized ("handIn ")){
...
}
}
Implementation Code
/**
* Implement synchronization lock in js. The default lock is 10 seconds.
* Example
* If (jsynchronized ("handIn ")){
...
*}
*/
Var locks = [];
Var LOCKTIME_DEFAULT = 1000*10;
Function jsynchronized (lockName, lockTime ){
If (getLock (lockName )){
Return false;
} Else {
SetLock (lockName, true );
SetTimeout (function (){
SetLock (lockName, false );
}, LockTime? LockTime: LOCKTIME_DEFAULT );
Return true;
}
}
/**
* Obtain a lock. If this lock is not added
*/
Function getLock (lockName ){
For (var I = 0; I <locks. length; I ++ ){
If (locks [I] [0] = lockName ){
Return locks [I] [1];
}
}
Locks [locks. length] = [lockName, false];
Return false;
}
/**
* Set a lock. If this lock is not added
*/
Function setLock (lockName, lockValue ){
For (var I = 0; I <locks. length; I ++ ){
If (locks [I] [0] = lockName ){
Locks [I] [1] = lockValue;
Return;
}
}
Locks [locks. length] = [lockName, lockValue];
}
Here, the "handIn" parameter can be customized based on different functional areas.
Does it feel a bit like java synchronized?
Author: bd_cool