thenewjavaman avatar

How to wait in a Node/JS thread

thenewjavaman

Published: 03 Jun 2018 › Updated: 03 Jun 2018

How to wait in a Node/JS thread

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.

Leave How to wait in a Node/JS thread to:

Written by

Self-taught programmer, sometimes is smart.

Read more #programming posts


Best Posts From thenewjavaman

We have not curated any of thenewjavaman's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From thenewjavaman