Let’s see if we can solve this from the outside in.
What might help is to store the functions that we want to run in an array. The params to the function could be stored in there too.
After developing this idea, the following code seem like it might do the job:
var delayedFuncs = [];
function triggerNextDelayedFunc() {
if (delayedFuncs.length < 1) {
return;
}
var delayedFunc = delayedFuncs.shift();
var func = delayedFunc.func;
var params = delayedFunc.params;
var delay = 1500;
setTimeout(triggerWrapper(func, params), delay);
}
While putting that code together, it became natural to refer to the function and the parameters of the delayedFunc object as separate parts, in the following kind of structure:
{
func: someFunc,
params: [param1, param2]
}
The timeout requires a function, so we can return a function from the triggerWrapper.
function triggerWrapper(func, params) {
return function () {
...
};
}
That returned function is from where we’ll run the func with its parameters.
After it’s finished running, we’ll want to also run the triggerNextDelayedFunc() function again.
function triggerWrapper(func, params) {
return function () {
func.apply(params);
triggerNextDelayedFunc();
};
}
We should now be able to add the username/email/password to the array.
delayedFuncs.push({
func: checkusername,
params: [username]
});
delayedFuncs.push({
func: checkemail,
params: [email]
});
delayedFuncs.push({
func: checkpassword,
params: [password]
});
It would be better if we used a separate function to add each delayed function, so that we can just pass it the name of the function and an array of parameters.
function addDelayedFunc(func, params) {
delayedFuncs.push({
func: func,
params: params
});
}
addDelayedFunc(checkusername, [username]);
addDelayedFunc(checkemail, [email]);
addDelayedFunc(checkpassword, [password]);
After adding some fake functions to do the username/email/password stuff, we end up with the following code