pigeonburger
pigeonburger

Reputation: 736

Perform function if event is not called within time period

I have a data fetching program in nodejs, and I want it to perform a function if an event has not happened within a certain amount of time.

console.log("Fetching data.....");

// "verify" event called when data has been successfully found
fetcher.on("verify", function() {
    console.log("Data found!");
    process.exit(1);
});

So what I want to do is if the verify event is not called within 10 seconds, do console.log("Fetching the data is taking longer than expected");

How can I go about doing this?

Upvotes: 0

Views: 116

Answers (1)

dave
dave

Reputation: 64657

Just set a timeout, and clear it when verify is called (or don't, since you are exiting the process anyways):

console.log("Fetching data.....");

const timeout = setTimeout(() => {
    console.log("Fetching the data is taking longer than expected");
}, 10000);

// "verify" event called when data has been successfully found
fetcher.on("verify", function() {
    clearTimeout(timeout);
    console.log("Data found!");
    process.exit(1);
});

Upvotes: 1

Related Questions