HackTimer/HackTimer.js

79 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-06-28 21:54:41 +00:00
(function (workerScript) {
var worker,
fakeIdToCallback = {},
lastFakeId = 0;
2015-06-28 21:54:41 +00:00
if (typeof (Worker) !== 'undefined') {
function getFakeId () {
lastFakeId ++;
return lastFakeId;
2015-06-28 21:54:41 +00:00
}
try {
worker = new Worker (workerScript);
window.setInterval = function (callback, time) {
var fakeId = getFakeId ();
2015-06-28 21:54:41 +00:00
fakeIdToCallback[fakeId] = callback;
worker.postMessage ({
name: 'setInterval',
fakeId: fakeId,
time: time
});
return fakeId;
};
window.clearInterval = function (fakeId) {
if (fakeIdToCallback.hasOwnProperty(fakeId)) {
delete fakeIdToCallback[fakeId];
worker.postMessage ({
name: 'clearInterval',
fakeId: fakeId
});
}
2015-06-28 21:54:41 +00:00
};
window.setTimeout = function (callback, time) {
var fakeId = getFakeId ();
2015-06-28 21:54:41 +00:00
fakeIdToCallback[fakeId] = callback;
worker.postMessage ({
name: 'setTimeout',
fakeId: fakeId,
time: time
});
return fakeId;
};
window.clearTimeout = function (fakeId) {
if (fakeIdToCallback.hasOwnProperty(fakeId)) {
delete fakeIdToCallback[fakeId];
worker.postMessage ({
name: 'clearTimeout',
fakeId: fakeId
});
}
2015-06-28 21:54:41 +00:00
};
worker.onmessage = function (event) {
var data = event.data,
fakeId = data.fakeId,
callback;
if (fakeIdToCallback.hasOwnProperty(fakeId)) {
2015-06-28 21:54:41 +00:00
callback = fakeIdToCallback[fakeId];
}
if (typeof (callback) === 'string') {
try {
callback = new Function (callback);
} catch (e) {
console.error(e);
}
}
if (typeof (callback) === 'function') {
callback.call (window);
}
2015-06-28 21:54:41 +00:00
};
worker.onerror = function (event) {
console.log(event);
};
console.log('HackTimer.js by turuslan: Initialisation succeeded');
} catch (error) {
console.log('HackTimer.js by turuslan: Initialisation failed');
console.error(error);
}
} else {
console.log('HackTimer.js by turuslan: Initialisation failed - HTML5 Web Worker is not supported');
}
})('HackTimerWorker.js');