HackTimer/HackTimer.js

90 lines
2.4 KiB
JavaScript
Raw Normal View History

2015-06-28 21:54:41 +00:00
(function (workerScript) {
var worker,
fakeIdToCallback = {},
lastFakeId = 0,
logPrefix = 'HackTimer.js by turuslan: ';
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 /* , parameters */) {
var fakeId = getFakeId ();
fakeIdToCallback[fakeId] = {
callback: callback,
parameters: Array.prototype.slice.call(arguments, 2)
};
2015-06-28 21:54:41 +00:00
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 /* , parameters */) {
var fakeId = getFakeId ();
fakeIdToCallback[fakeId] = {
callback: callback,
parameters: Array.prototype.slice.call(arguments, 2)
};
2015-06-28 21:54:41 +00:00
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,
request,
parameters,
callback;
if (fakeIdToCallback.hasOwnProperty(fakeId)) {
request = fakeIdToCallback[fakeId];
callback = request.callback;
parameters = request.parameters;
}
if (typeof (callback) === 'string') {
try {
callback = new Function (callback);
} catch (error) {
console.log (logPrefix + 'Error parsing callback code string: ', error);
}
}
if (typeof (callback) === 'function') {
callback.apply (window, parameters);
}
2015-06-28 21:54:41 +00:00
};
worker.onerror = function (event) {
console.log (event);
2015-06-28 21:54:41 +00:00
};
console.log (logPrefix + 'Initialisation succeeded');
2015-06-28 21:54:41 +00:00
} catch (error) {
console.log (logPrefix + 'Initialisation failed');
console.error (error);
2015-06-28 21:54:41 +00:00
}
} else {
console.log (logPrefix + 'Initialisation failed - HTML5 Web Worker is not supported');
2015-06-28 21:54:41 +00:00
}
})('HackTimerWorker.js');