Naively, you can implement sleep() with a while loop same as the pausecomp function (this is basically the same):
const sleep = (seconds) => {
const waitUntil = new Date().getTime() + seconds * 1000
while(new Date().getTime() < waitUntil) {
// do nothing
}
}
And you can use the sleep() method like so:
const main = () => {
const a = 1 + 3
// Sleep 3 seconds before the next action
sleep(3)
const b = a + 4
// Sleep 4 seconds before the next action
sleep(4)
const c = b + 5
}
main()
This is how I imagine you would use the sleep function, and is relatively straightforward to read. I borrowed from the other post Sleep in JavaScript - delay between actions to show how you may have been intending to use it.
Unfortunately, your computer will get warm and all work will be blocked. If running in a browser, the tab will grind to a halt and the user will be unable to interact with the page.
If you restructure your code to be asynchronous, then you can leverage setTimeout() as a sleep function same as the other post.
// define sleep using setTimeout
const sleep = (seconds, callback) => setTimeout(() => callback(), seconds * 1000)
const main = () => {
const a = 1 + 3
let b = undefined
let c = undefined
// Sleep 3 seconds before the next action
sleep(3, () => {
b = a + 4
// Sleep 4 seconds before the next action
sleep(4, () => {
c = b + 5
})
})
}
main()
As you said, this isn't what you wanted. I modified the example from Sleep in JavaScript - delay between actions to show why this might be. As you add more actions, you will either need to pull your logic into separate functions or nest your code deeper and deeper (callback hell).
To solve "callback hell", we can define sleep using promises instead:
const sleep = (seconds) => new Promise((resolve => setTimeout(() => resolve(), seconds * 1000)))
const main = () => {
const a = 1 + 3
let b = undefined
let c = undefined
// Sleep 3 seconds before the next action
return sleep(3)
.then(() => {
b = a + 4
// Sleep 4 seconds before the next action
return sleep(4)
})
.then(() => {
c = b + 5
})
}
main()
Promises can avoid the deep nesting, but still doesn't look like the regular synchronous code that we started with. We want to write code that looks synchronous, but doesn't have any of the downsides.
Let's rewrite our main method again using async/await:
const sleep = (seconds) => new Promise((resolve => setTimeout(() => resolve(), seconds * 1000)))
const main = async () => {
const a = 1 + 3
// Sleep 3 seconds before the next action
await sleep(3)
const b = a + 4
// Sleep 4 seconds before the next action
await sleep(4)
const c = b + 5
}
main()
With async/await, we can call sleep() almost as if it was a synchronous, blocking function. This solves the problem you may have had with the callback solution from the other post and avoids issues with a long-running loop.