const SELECTOR_POLLING_INTERVAL = 5000;

export function pollForSelector(
  selector: string,
  selectorPollingTimeLimit: number,
  onSuccess: (element: Element) => void
) {
  const deadline = Date.now() + selectorPollingTimeLimit * 1000;

  const interval = setInterval(() => {
    const element = document.querySelector(selector);

    if (Date.now() > deadline) {
      clearInterval(interval);
      console.error(`Не удалось найти элемент ${selector} для вставки виджета`);
      return;
    }
    if (!element) {
      return;
    }

    clearInterval(interval);
    onSuccess(element);
  }, SELECTOR_POLLING_INTERVAL);
}
