Timers

Use SBCanvas timers instead of raw setTimeout/setInterval. They’re tracked per widget and automatically cleaned up when the widget unloads, preventing dead DOM callbacks and memory leaks.

setTimeout

const id = SBCanvas.setTimeout(() => {
  hideAlert();
}, 5000);

setInterval

const id = SBCanvas.setInterval(() => {
  updateClock();
}, 1000);

clearTimer

Cancel either a timeout or interval:
SBCanvas.clearTimer(id);

Why Not Raw setTimeout?

// Bad: if widget unloads before this fires, the callback hits a dead DOM
setTimeout(() => document.getElementById('el').remove(), 5000);

// Good: cancelled automatically when widget unloads
SBCanvas.setTimeout(() => document.getElementById('el').remove(), 5000);
When a widget unloads, all pending timeouts and intervals are cleared. No manual cleanup needed.

Example: Auto-Hide Alert

SBCanvas.activities.on('follow', (activity) => {
  const el = document.getElementById('alert');
  el.textContent = `${activity.username} followed!`;
  el.classList.add('show');

  SBCanvas.setTimeout(() => {
    el.classList.remove('show');
  }, 5000);
});

Example: Live Clock

SBCanvas.ready(() => {
  const clock = document.getElementById('clock');

  SBCanvas.setInterval(() => {
    clock.textContent = new Date().toLocaleTimeString();
  }, 1000);
});

Example: Polling External Data

SBCanvas.ready(() => {
  async function poll() {
    const res = await SBCanvas.http('https://api.example.com/viewers', { method: 'GET' });
    if (res.ok) {
      document.getElementById('viewers').textContent = res.body.count;
    }
  }

  poll();
  SBCanvas.setInterval(poll, 30000);
});

API Reference

MethodReturnsDescription
SBCanvas.setTimeout(fn, ms)numberSchedule a one-shot callback
SBCanvas.setInterval(fn, ms)numberSchedule a repeating callback
SBCanvas.clearTimer(id)voidCancel a timeout or interval