Home > Software engineering >  Execute a function once the timer runs zero
Execute a function once the timer runs zero

Time:10-14

I have a database entry that has the following data:

{
   _id:"fdjshbjds564564sfsdf",
   shipmentCreationTime:"12:17 AM"
   shipmentExpiryTime:"12:32 AM"
}

What I want to do is create a timer from the front end (ReactJS) on the basis of creation and expiry time provided in the data set. And once the timer runs zero, I want to execute an API call back to the backend.

The function is as follows:

exports.expireShipmentOffer = async (req,res) => {

    const { shipmentOfferId } = req.body;

    try {
        const updatedOffer = await ShipmentOrder.findOneAndUpdate({_id: shipmentOfferId} , {$set:{status:'Expired'}} , {new: true})
       
        const newNotification = await Notification({accountId: updatedOffer.accountId ,  notificationHeader: ` Shipment Order Expired `  , notificationMessage:`Your Shipment Request ${shipmentOfferId} has been expired due to no response from the carrier` , timeAndDate : moment().format('LLL'), actionPath:`/shipmentOffer/${updatedOffer._id}`})
    
        await newNotification.save();
    
        res.json({
            status: 200,
            message: updatedOffer
        })
    } catch (error) {
        res.json({
            status: 500,
            message:error.message
        })
    }

}

What can I do to achieve this?

CodePudding user response:

You can achieve this in different ways , one of them is to register a callback and use setTimout() function based on your dataset , you then can execute the request inside this function

CodePudding user response:

I did not understand very well.

Do you want to create a Countdown or Timer?

If if you want to create a Countdown, save the value in a state and call your API when it is zero.

But if you want to create a timer, I suggest you use Promise docs

const tiemr = () => {
    return new Promise(done => {
        setTimeout(() => {
            done(callYourAPI());
        }, 5000); // after 5s
    })
}
  • Related