I'm trying to schedule a bunch of tasks to run on time intervals using changing config data as input:
let configData = initConfig(); // Initialize configuration data from file
setInterval(taskA.bind(null, configData), TASK_A_WAIT); // Task using config data
setInterval(taskB.bind(null, configData), TASK_B_WAIT); // Task using config data
setInterval(taskC.bind(null, configData), TASK_C_WAIT); // Task using config data
setInterval(refreshConfig.bind(null, (error, result) => { // Update config data
if (error) handleError(error);
else configData = result;
}), CONFIG_REFRESH_WAIT);
The goal is for the configuration data to update on interval using the last setInterval(), so that the first three setInterval()'s always have the latest data to work with. But will it work?
In the semantics of javascript, will the above actually bind the function to the latest configData object anew with every interval? When do binds happen in such a scenario?
Since bind() isn't wrapped in another function, it is synchronously executed in-place.
Task functions are bound to original configData. If it's reassigned with configData = result, this doesn't affect bound functions.
Task functions should be wrapped with functions to get reassigned configData:
setInterval(() => { taskA(configData) }, TASK_A_WAIT)
Another option that will work with bind is to preserve same reference for configData object, this will work only if initial configData is an object:
setInterval(refreshConfig.bind(null, (error, result) => {
...
Object.assign(configData, result);
}), CONFIG_REFRESH_WAIT);
If there's a chance that configData already has properties that possibly won't be overridden, it should be cleared first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With