How to wait in a Node/JS thread

in #programming6 years ago (edited)

intro

So I'm currently writing an Electron application (info here), and I had a need to stop my JS thread for just 250ms (0.25s). In Python, I simply would have:
time.sleep(.25)

the rub

But I'm not used to writing to JS, so I thought linearly; I have to stop and wait, using a single command. However, that's not the case here. As it turns out, there are three options for those of you who found this thread:

  1. var run = setTimeout(function1, 250);
    This just runs the function after the timeout, in milliseconds. I haven't seen this interpretation of sleeping in any other language, which is why I was surprised at seeing this.
  2. var run = setInterval(function1, 250);
    This continuously runs the function at that interval until stopped by the thread. It's super similar to the first option but saves us a loop. This is what I ended up using in my code; it fits nicely because I have to sync my page to a database at that interval, which saves me that extra, awkward, while loop.
  3. var waitTill = new Date(new Date().getTime() + seconds * 1000);
    while(waitTill > new Date()) {}
    Credits to this method go here. If you need an easy solution, this will simply halt the process. I "don't recommend it," because it's "not acceptable" and "has better alternatives." Honestly, just use this if you want to.

Comment/upvote if you found this tidbit useful. I'll start posting more regularly now that school is out, so expect some in-depth, interesting articles soon.

Sort:  

Congratulations @thenewjavaman! You received a personal award!

1 Year on Steemit

Click here to view your Board of Honor

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @thenewjavaman! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!