paint-brush
Let’s make a JavaScript Wait functionby@jsborked
161,003 reads
161,003 reads

Let’s make a JavaScript Wait function

by Just Chris
Just Chris HackerNoon profile picture

Just Chris

@jsborked

November 11th, 2017
Read on Terminal Reader
Read this story in a terminal
Print this story
Read this story w/o Javascript
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Async/await and its underlying use of promises are taking the JS world by storm. Now supported by a majority of client and server <a href="https://hackernoon.com/tagged/js-platforms" target="_blank">JS platforms</a>, callback <a href="https://hackernoon.com/tagged/programming" target="_blank">programming</a> is becoming a thing of the past.

Company Mentioned

Mention Thumbnail
Mind
featured image - Let’s make a JavaScript Wait function
1x
Read by Dr. One voice-avatar

Listen to this story

Just Chris HackerNoon profile picture
Just Chris

Just Chris

@jsborked

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.

image

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:

image

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 syntaxvar prom = wait(2000) // prom, is a promisevar showdone = ()=>console.warn('done')prom.then(showdone)



// same thing, using await syntaxawait 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 = 1var y = 2await 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!')elsesetTimeout(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.

L O A D I N G
. . . comments & more!

About Author

Just Chris HackerNoon profile picture
Just Chris@jsborked

TOPICS

THIS ARTICLE WAS FEATURED IN...

Permanent on Arweave
Read on Terminal Reader
Read this story in a terminal
 Terminal
Read this story w/o Javascript
Read this story w/o Javascript
 Lite
Fullstackfeed
Site-builder
Boarderlinesurfskate
Yemreak
Imooc
Aryan
X REMOVE AD