You schedule two callbacks:
wait(500, function(x) {return x + 5}) // execute after 500ms
wait(250, function(x) {return x * 2}) // execute after 250ms
The first argument is the time after which the callback will be run. Since the second wait
call has the lower first argument, it runs first.
At 250ms or so, since result
starts at 10, the x * 2
multiplies result
by 2, getting you to 20.
Then, at 500ms or so, the x + 5
runs, getting you to 25.
If you want to be able to do this sort of thing such that the code appears to run more sequentially, use Promises and await
instead:
let result = 10;
function wait(time,f) {
return new Promise(resolve => setTimeout(() => {
result = f(result);
resolve();
}, time));
}
(async () => {
await wait(250, x => x * 2);
await wait(250, x => x + 5);
console.log(result);
})();