Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs setTimeout unique ID for clearTimeout

I have a NodeJS app for scheduling tasks, the task is used to create a booking, that booking could be cancelled before the task is performed, there's a possibility of having hundred of thousands of tasks (e.g. 67 tasks created in one minute)

The way i'm doing it is by calling this function:

runOnDate = function (dateIn){
    console.log('scheduling')
    var now = (new Date()).getTime();
    var booking = setTimeout(startBooking , (dateIn - now));

    //Lets try to catch the ID number of booking
    console.log(booking) // Shows [object Object]
    console.log(booking.timeoutID) // Shows undefined
}

My problem starts if i have to cancel one of this setTimeout, i know the setTimeout returns a Number for using it with clearTimeout() .

But i can't seem to get the number, is there a way to create a timer with an unique ID i can use for clearTimeout() or other way to call clearTimeout on a particular setTimeout?

like image 675
user1220740 Avatar asked Apr 25 '26 00:04

user1220740


1 Answers

clearTimeout should be passed whatever is returned from setTimeout. node does not return a number for its timer, instead it returns an object. So in this case you should be doing clearTimeout(booking) by passing it the object. In browsers it returns a number.

setTimeout/clearTimeout are part of the browser APIs and are not JS standards, so there is no requirement that they even be provided in Node, let alone that they have the same arguments/return values. In node timers result in an object because timers can have methods.

Given what you've said, I'd also suggest you consider using some kind of task queue rather than starting tons of timers. You would be better off maintaining a queue of tasks, and pulling things off of the queue as their start time arrives by just maintaining a single timer.

like image 94
loganfsmyth Avatar answered Apr 27 '26 15:04

loganfsmyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!