DEV Community

Cover image for NodeJs and setTimeout
.·. Felipe Paz .·.
.·. Felipe Paz .·.

Posted on

NodeJs and setTimeout

Everybody hello, me again here!!! =D =D =D

First of all, I actually realized that sometimes I look like Master Yoda speaking English. That's weird =( =D =( =D ...

Well, let's talk about what's really important.

Everybody knows that even if NodeJs interprets javascript, a lot of js functionalities don't work on the Node platform once they are compiled by browser engines;

Ok, ok... there's no news here!!!

But last night I was playing with Node and reading its documentation until I saw a package called timers.

Hummmmm, interesting. What does it do?

I kept my reading and noticed a function setTimeout. How so? Could be the same function that runs on wer browsers?

Let's check it out!!!

With this info, I created a simple express server with one single POST method and the body with json containing a timer key.

Annnnnnd yeeeeeees, Nodejs has a native setTimeout and it works like it runs on web browsers.

So, my example was like that:

const express = require('express');
const http = require('http');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post('/', async (req, res) => {
  const { timer } = req.body;

  const promise = () => new Promise((resolve) => {
    setTimeout(function () {
      resolve(res.status(200).send("weeeeeeeeeeeee"));
    }, timer);
  });

  try {
    await promise();
  } catch (err) {
    res.status(500).send('my bad ...');
  }
});

const server = http.createServer(app);

server.listen(3000, () => console.log('running'));
Enter fullscreen mode Exit fullscreen mode

And, our request should be like that:

curl -i -X POST localhost:3000 -H "Content-type: application/json" -d '{"timer": 1000}'
Enter fullscreen mode Exit fullscreen mode

It's a pretty simple example but as we can see, in the body of request we have an object with the key timer and this is the time that express will take to respond the request.

So, yes... we have a way to use setTimeout on the Node engine.

Why should I use it? I don't know and it doesn't matter, I just know that it exists!!!!!!

See you next chapter when I'll use this same example to work with AbortController.

Top comments (2)

Collapse
 
urielsouza29 profile image
Uriel dos Santos Souza

node API timers/promises

const { setTimeout } = require('timers/promises');

await setTimeout(1000); 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
curiousdev profile image
CuriousDev

Thank you, so it is basically the same as in browser.