Requirement:
I need to write a function that takes an array of objects. Each item in the array has a state; if state === 'processing'
, a delay of 2 seconds is implemented before moving on to the next item. In other words, I actually need to block execution of the function for 2 seconds before looking at the next element in the array. When an element's state is not 'processing', the function returns an object and no further array elements are looked at.
The problem:
I can't think of any way to create a delay without using asynchronous approaches. I've written code (see below) which relies on Promise
, but this does not satisfy the requirements, as with any asynchronous approach the Promise will return immediately; the delay only delays promise resolution not function execution. Thus, I wonder if there isn't a way of doing this synchronously, of blocking return of the function until after any delays are implemented.
My question:
Is there a way to accomplish this synchronously, to block execution of the code for a specified period of time before returning an object?
My code, which uses an asynchronous approach:
function wait(delay, callback, arg) {
return new Promise(resolve => {
setTimeout(() => {
resolve(callback(arg));
}, delay);
});
}
function getProcessingPage(data) {
const currentObj = data[0];
const state = currentObj.state;
if (state === 'processing') {
return wait(2000, getProcessingPage, data.slice(1));
}
return Promise.resolve({});
}
The solution:
Since this question has been closed (wrongly, in my opinion), it can not be answered, but I now have an answer. The answer is not performant in the least bit — it is not considered good practice and should never find its way into production code — but it does exactly what I needed to do for this exercise. The solution is to use while
to prevent any code execution during the desired delay. See below:
function wait(delay) {
const delayUntil = performance.now() + delay;
while (performance.now() < delayUntil) {
// do nothing, as the while statement blocks execution
}
}
function getProcessingPage(data) {
const currentObj = data[0];
const state = currentObj.state;
if (state === 'processing') {
wait(2000);
return getProcessingPage(data.slice(1));
}
return {};
}