You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Timer为何仅执行一次?需实现每20秒执行回调方法

Fixing Your Callback to Run Every 20 Seconds

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:16:11