Express callback delaying with setTimeout

I'm working on a route that involves setting a data attribute called "active" to true initially, but then switching it to false after an hour. I'm curious if it's considered bad practice or feasible to use a setTimeout function within the express callback function like this:

app.get("/test", (req, res) => {

//Some code

SetTimeout(func, 3600);
});

I'm concerned about scalability - if this route is accessed frequently, will it become too costly? Appreciate any insights on this matter. Thanks!

Answer №1

When storing values in a database, it is not recommended to create a timer for each entry in the node that resets the value. This is especially true for long-lasting timers. Session-like or related data that needs to persist for longer periods should not be held in the memory of the node process.

If your site receives frequent visitors, there may be multiple timers running concurrently. Restarting the application can either result in losing these timers or require waiting until they finish before accepting any new ones.

Switching to clustered mode is not a viable solution as calling a route twice could lead to the requests being handled by different processes, causing inconsistencies with timeouts set by each process.

A more efficient approach would be to add a timestamp to the database and implement a cleanup timer that manages all entries.

Answer №2

It appears that setting one timer may be sufficient in this case, assuming the 'hour' begins with the initial request.

let timer = null
let data = true

app.get("/test", (req, res) => {

  //Some code
  if (!timer) {
    timer = setTimeout(() => {data=false}, 3600);
  }
});

Alternatively, for multiple users, it is possible to avoid setting numerous timers by utilizing a hash with timestamps and checking it for each request or using a separate interval timer.

// init
let timers = {}

// in request
if (!timers[user]) {
    timers[user] = new Date().getTime() / 1000 + 3600
}
else if (timers[user] <= new Date().getTime() / 1000)
{
    // update db, etc
}


// or poll for expirations in separate single timer routine
let now = new Date().getTime() / 1000
Object.keys(timers).forEach(user => {
  if (timers[user] <= now) {
    // update db, etc
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The request to http://localhost:3000/cartdata has encountered an internal server error (500) in the isAxiosError.js file at line

Error Image I'm currently working on developing a shopping cart feature, and I've encountered an issue when transferring data from the client side to the server side. Despite the cart data being successfully updated in the session, an internal se ...

The Electron application is experiencing difficulties locating the module at /resources/app/index.js

Just started my journey with electron and successfully created my first electron application. It runs perfectly fine with npm start, but I encounter issues when trying to execute it with npm run. (I am using Ubuntu Linux). The command line interface displa ...

Having trouble with sending emails using expressjs and nodejs

I'm encountering an issue with sending emails on the submit button in a website using expressjs and nodejs. When I try to send an email on the post call, I receive the following error in the console. I am utilizing nodemailer for sending the email. E ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Creating an attractive image carousel using jQuery or YUI for your website

I am searching for a javascript-based slideshow solution for images. I have received the following requirements: The slideshow should fade one image into another, looping back to the first image after all images have been displayed It must include naviga ...

Guide on passing a variable from AJAX response to a JavaScript function when a user clicks

I need to send the value of a variable as a parameter to a javascript function when clicking on a link. The value is obtained from an AJAX response. However, I am encountering an error in the console stating that 'test' is not defined. var test ...

The error "Unable to create an instance of mssql.Schema" indicates that the

Seeking assistance from experienced ReactJS developers to address the issue outlined below. The code provided is based on a tutorial I was following. Despite numerous attempts, I have been unable to resolve the issue. Here is the code snippet from User.js ...

When located at the bottom of a page, the Div element fails to display

I need some help with my javascript code. I am working on creating a scrollable panel that closes when scrolled and reveals a #toTop div when the bottom of the page is reached. Below is the function code I have written, but for some reason, the #toTop div ...

Error in Babel-Loader when executing npm run build

Not being a webpack expert, I decided to upgrade from V3 to V4. After fixing the depreciation errors in my webpack config, I hit a roadblock with a syntax error from babel-loader: Module build failed (from ./node_modules/babel-loader/lib/index.js): ...

Issue when attempting to update user profile picture using Mongoose schema and Cloudinary

updateProfile: async function(req, res) { try { const update = req.body; const id = req.params.id; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.&a ...

Analyzing Compatibility and Ensuring Security

I recently started using Parse and have been exploring the documentation and answered questions. However, I still have a couple of inquiries on my mind. Firstly, I discovered that the Javascript SDK does not function on IE9 and IE8 without an SSL certific ...

Why opt for ref.current over directly applying the condition?

I'm curious as to why the code uses if (ref.current && !ref.current.contains(event.target)) rather than if (!ref.current.contains(event.target) function useOutsideAlerter(ref) { useEffect(() => { // Function for click event function hand ...

I often struggle with creating social media buttons using Material UI

Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library (IconButton / AlarmIcon). import './App.css'; impor ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

Animate my banner images only after they have fully loaded using Jquery

I recently came across a banner image slideshow in jQuery, but it seems to be animating even before the images are fully loaded. This results in the slideshow displaying image descriptions without the actual images themselves. Can anyone help me modify th ...

Failed to load Gulpfile.js in the Task Runner Explorer of Visual Studio 2019 version 16.6.2

Displayed below is the result in the output error window. Failed to execute "D:\TortSVN\Oil Diversity\Main Web App\LatsetOildiversity\Gulpfile.js"... cmd.exe /c gulp --tasks-simple fs.js:27 const { Math, Object } = primordials; ...

Ways to specify the default value for a component

A sample of my custom component code (Amount.tsx) is shown below: const Price = ({ price, prevPrice }) => { return ( <div className="product-amount"> <div className="price"> {prevPrice ? (<del class ...

Video background mute feature malfunctioning

I've searched through numerous resources and reviewed various solutions for this issue, yet I still haven't been able to figure it out. Could someone please guide me on how to mute my youtube embedded video? P.s. I am a beginner when it comes to ...

Guidelines for showcasing a map on my website with the option for users to select a specific country

Is there a method to showcase a global map on my site and let the user select a country to receive relevant information? I am aware of embedding Google Maps, however, it includes unnecessary controls like zooming which I prefer not to inconvenience the us ...

Having trouble with Vue Router at the root path ("/") while utilizing Quasar Server-Side Rendering (SSR)?

THE ISSUE AT HAND I have a Quasar CLI (Webpack) setup for my app, and everything runs smoothly in SPA mode. However, when I switch to SSR, an unexpected issue arises. The Vue Router redirect from path "/"" to "/index" does not function as expected. Instea ...