Before you go, check out these stories!

0
Hackernoon logoLet’s make a JavaScript Wait function by@jsborked

Let’s make a JavaScript Wait function

Author profile picture

@jsborkedJust Chris

Async/await and its underlying use of promises are taking the JS world by storm. Now supported by a majority of client and server JS platforms, callback programming is becoming a thing of the past.

Surely, callback based programming is ugly.

If you haven’t already, it’s worth getting your mind around async/await and promises. I personally haven’t been a huge fan of promises, before async/await, as you can get code like this:

Better than callback hell, but not aesthetically pleasing.

There are many good intros to async/await available, so I won’t go into a full discussion here, but the 15 sec. tutorial is, you have your function return a promise, and then use await (inside an async function) to call the promise.

These examples will also make use of a new-ish JS feature, arrow functions. 
If you’re unfamiliar with writing in this style, basically this:

function(a) { return console.log(a) }

now use this,

(a) => console.log(a)

With that, we are ready to make our Wait function.

Using a Wait function, also called Sleep in some environments, is very easy to understand, read, and write. It’s easy to make sense of it. We want execution to wait for a period of time.

Just set a timeout for resolving the promise. We can provide ms for how long to wait.

var wait = ms => new Promise((r, j)=>setTimeout(r, ms))

wait(2000) returns a promise, that will be resolved in 2000ms (2 sec.)

// Promise syntax
var prom = wait(2000) // prom, is a promise
var showdone = ()=>console.warn('done')
prom.then(showdone)
// same thing, using await syntax
await wait(2000)
console.warn('done')

Using async/await syntax, which is nicer than promise’s .then() syntax. Let’s wrap it in an Immediately Invoked function for brevity.

(async () => { await wait(2000); console.warn('done') })()

Or amidst regular code

var x = 1
var y = 2
await wait(2000)
console.warn(x)

What if we want to wait on an event, instead of just waiting x ms of time? 
Just control when the promise is resolved.

We may even timeout the call, if the event never occurs, so the code doesn’t wait forever.

Let’s say we want to wait on a DOM element to be set to “Hello World” in a web page. We’ll check every 100ms and timeout after 2 seconds.

<div id=a>s</div>
<script>
var e = document.querySelector('#a')

var waitForHello = timeoutms => new Promise((r, j)=>{
var check = () => {
console.warn('checking')
if(e.innerHTML == 'Hello world')
r()
else if((timeoutms -= 100) < 0)
j('timed out!')
else
setTimeout(check, 100)
}
setTimeout(check, 100)
})
//setTimeout(()=>{e.innerHTML='Hello world'}, 1000)
  (async ()=>{
a.innerHTML = 'waiting..'
waitForHello(2000)
})()

</script>

Un-commenting the setTimeout line will set the DIV after 1 second, otherwise will time out.

As you can see, async/await opens up great new possibilities in your code.

Tags

Become a Hackolyte

Level up your reading game by joining Hacker Noon now!