Skip to content

Instantly share code, notes, and snippets.

@houkanshan
Created September 6, 2012 15:41
Show Gist options
  • Save houkanshan/3657539 to your computer and use it in GitHub Desktop.
Save houkanshan/3657539 to your computer and use it in GitHub Desktop.
限制单实例运行
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="./test.js" type="text/javascript"></script>
</head>
<body>
<span id="test"></span>
</body>
</html>
/*
* http://www.douban.com/people/2790109/status/1004046271/
* 一个应用多个实例间只允许一个实例运行
* localStorage.clear()的时候会出问题,没有做恢复~
* runner其实不需要每次都检查localStorage.runningId
*/
window.onload = function(){
// if localStorage.clear(), all will be stoped,
// create a new page will restart
testEl = document.getElementById('test');
var CHECK_TIME = 500;
var TIMEOUT_TIME = 1000;
var myId;
var runningId = parseInt(localStorage.runningId, 10);
var lastRunnerId = parseInt(localStorage.lastId, 10);
//id init
if(runningId && lastRunnerId){
myId = lastRunnerId + 1;
}
else {
myId = 1;
localStorage.runningId = myId;
}
localStorage.lastId = myId;
localStorage.timeStamp = localStorage.timeStamp || Date.now();
setInterval(function(){
//check id
var runningId = parseInt(localStorage.runningId, 10);
if (runningId === myId){
// i'm running
localStorage.timeStamp = Date.now();
run();
}
else {
// i'm waiting
if(Date.now() - localStorage.timeStamp > TIMEOUT_TIME){
// check timeout, be the runner
localStorage.timeStamp = Date.now();
localStorage.runningId = myId;
}
else{
// still waiting
wait();
}
}
}, CHECK_TIME);
};
function run(){
var msg = 'i\'m runnging';
testEl.innerText = msg;
console.log(msg);
};
function wait(){
var msg = localStorage.runningId + ' is running~';
testEl.innerTest = msg;
console.log(msg);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment