Javascript code to reload modal window for 5 seconds

Dani AI

Generated

The original request from is ambiguous and, as and pointed out, the solution depends on which modal library and what "reload" means. Two common patterns are shown below: (A) auto-refresh the modal content every 5 seconds; (B) show the modal and automatically close it after 5 seconds. Important: always clear timers when the modal closes to avoid duplicate intervals and memory leaks.

For periodic content refresh (safe for AJAX-backed content):

const modalBody = document.querySelector('#myModal .modal-body');
let refreshId = null;

function startAutoRefresh(url, ms = 5000) {
  stopAutoRefresh();
  refreshId = setInterval(async () => {
    try {
      const r = await fetch(url, { cache: 'no-store' });
      if (!r.ok) throw new Error(r.statusText);
      modalBody.innerHTML = await r.text();
    } catch (err) {
      console.error('Modal refresh error:', err);
    }
  }, ms);
}

function stopAutoRefresh() {
  if (refreshId) { clearInterval(refreshId); refreshId = null; }
}

// Hook into your modal's close event to call stopAutoRefresh()

To show the modal then hide after 5 seconds (simpler):

function showModalFor5s(showFn, hideFn) {
  showFn();
  setTimeout(hideFn, 5000);
}

// Example with Bootstrap/jQuery:
// showModalFor5s(() => $('#myModal').modal('show'), () => $('#myModal').modal('hide'));

Cautions: confirm element selectors exist before starting timers, throttle refresh frequency to avoid server overload, handle fetch errors gracefully, and bind stopAutoRefresh to the modal's close event (for Bootstrap listen to "hidden.bs.modal"). For reference on timers see setInterval - MDN.

Recommended Answers

All 2 Replies

What kind of modal window do you want to reload? What are it's content? Be specific, precise and tell more details of the things you want to happen.

yeah, make it specific..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.