Timer为何仅执行一次?需实现每20秒执行回调方法
Hey there! Let's get that callback of yours running reliably every 20 seconds. Depending on your use case, here are two go-to methods:
1. Simple & Direct: setInterval
This is the most straightforward way to repeat a function at a fixed interval. Here's how to implement it:
// Define your callback function function myCallback() { console.log("Callback fired!"); // Add your actual business logic here } // Schedule it to run every 20 seconds (20000 milliseconds) const intervalId = setInterval(myCallback, 20000); // To stop the interval later (if needed), use: // clearInterval(intervalId);
Heads up: If your callback takes longer than 20 seconds to finish, subsequent calls will pile up and run back-to-back once the first one completes. This might not be ideal if your logic is time-consuming.
2. More Reliable: Recursive setTimeout
This method waits until your callback finishes executing before scheduling the next run, preventing any backlog. It’s great for callbacks with asynchronous logic (like API calls):
Basic recursive setup
function myCallback() { console.log("Callback executed!"); // Your core logic here // Schedule the next run after this one finishes setTimeout(myCallback, 20000); } // Start the first execution myCallback();
With a stop control
If you need to be able to pause the loop later, add a flag:
let keepRunning = true; function controlledCallback() { if (!keepRunning) return; // Exit if we've stopped console.log("Controlled callback running!"); // Your logic here setTimeout(controlledCallback, 20000); } // Start the loop controlledCallback(); // To stop it later: // keepRunning = false;
For asynchronous callbacks
If your callback uses async/await (like fetching data), make sure to schedule the next run after the async operation completes:
async function asyncCallback() { try { // Example: Fetch data from an API const response = await fetch("/your-api-endpoint"); const data = await response.json(); console.log("Fetched data:", data); } catch (error) { console.error("Error in callback:", error); } finally { // Schedule next run regardless of success/failure setTimeout(asyncCallback, 20000); } } // Start the async loop asyncCallback();
内容的提问来源于stack exchange,提问作者Francisco Vargas

