ziko
Version:
A versatile JavaScript library offering a rich set of Hyperscript Based UI components, advanced mathematical utilities, interactivity ,animations, client side routing and more ...
56 lines (47 loc) • 1.72 kB
JavaScript
class UseThread {
constructor() {
const workerCode = `
this.onmessage = function(e) {
const { id, funStr, args, close } = e.data;
try {
const func = new Function("return " + funStr)();
const result = func(...args);
postMessage({ id, result });
} catch (error) {
postMessage({ id, error: error.message });
} finally {
if (close) self.close();
}
}
`;
const blob = new Blob([workerCode], { type: "text/javascript" });
this.
this.
const { id, result, error } = e.data;
const callback = this.
if (!callback) return;
callback(result, error);
this.
});
}
call(func, callback, args = [], close = true) {
if (typeof func !== "function") throw new TypeError("func must be a function");
const id = ++this.
this.
this.
id,
funStr: func.toString(),
args,
close
});
return this;
}
terminate() {
this.
}
}
const useThread = (func, callback, args = [], close = true) => new UseThread().call(func, callback, args, close);
export { UseThread, useThread };