Skip to content

Instantly share code, notes, and snippets.

@Pamblam Pamblam/thread.js
Last active Jun 25, 2019

Embed
What would you like to do?
Creating disposable threads in javascript.
// Call the function with at least one parameter.
// The last parameter must be a function that will run on it's own thread
// Any params that are passed to Thread() will be available in the thread function
// The last param of the thread function must be
function Thread(){
return new Promise((resolve, reject)=>{
var args = Array.from(arguments);
var func = args.pop();
if(typeof func !== "function") throw new Error("Invalid function");
var fstr = func.toString();
var mainBody = fstr.substring(fstr.indexOf("{")+1, fstr.lastIndexOf("}"));
var paramNames = fstr.substring(fstr.indexOf("(")+1, fstr.indexOf(")")).split(",").map(p=>p.trim());
var doneFunct = paramNames.pop();
if(paramNames.length !== args.length) throw new Error("Invalid number of arguments.");
var workerStr = `var ${doneFunct} = function(){
var args = Array.from(arguments);
postMessage(args);
};
self.onmessage = function(d){
var [${paramNames.join(", ")}] = d.data;
${mainBody}
};`;
var blob = new Blob([workerStr], {type: 'application/javascript'});
var worker = new Worker(URL.createObjectURL(blob));
worker.onerror = reject;
worker.onmessage = (d)=>{
resolve(...d.data);
worker.terminate();
};
worker.postMessage(args);
});
}
new Thread("this is a message", 2, function(message, delaySeconds, exit){
setTimeout(()=>{
exit(message.split('').reverse().join(''));
}, delaySeconds * 1000);
}).then(data=>{
console.log(data);
}).catch(err=>{
console.log('error: ', err);
});
// Can be used with or without "new"
Thread(function(exit){
console.log("logging from thread");
setTimeout(exit, 1000);
}).then(data=>{
console.log('done');
}).catch(err=>{
console.log('error: ', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.