Last active
May 18, 2023 13:21
-
-
Save Pamblam/683d5ae429448adfa6d6e7fb30de39b2 to your computer and use it in GitHub Desktop.
Creating disposable threads in javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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