htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Trigger every X second with a limit (e.g. every 30 seconds, but only 10 times)

Open violuke opened this issue 2 years ago • 3 comments

I'm not sure if this is possible yet, but if not, I'd love to be able to set a condition of how many times something can be triggered. Much like once (as per) but for a number of times that I provide.

Maybe something like:

<div hx-get="/latest_updates" hx-trigger="every 30s max:10"></div>

Thank you :)

violuke avatar Feb 18 '23 22:02 violuke

I need this. My element wants to update itself every second, but stop doing it in case of inactivity, perhaps user has left computer and forget to close tab.

7flash avatar Jan 12 '24 12:01 7flash

I think it can be implemented based on this example using conditional trigger incrementing a counter variable with every request?

<div hx-get="/latest_updates" hx-trigger="every 1s [someConditional]">
  Nothing Yet!
</div>

7flash avatar Jan 12 '24 12:01 7flash

You can write some js to handle a custom event:

<div id="polling-element" hx-get="/example" hx-trigger="my-custom-event from:body">
    Triggered by custom event...
</div>

<script>
    // JavaScript code to create and fire the custom event
    document.addEventListener('DOMContentLoaded', function() {
        var intervalId;
        var startTime = Date.now();

        // Function to create and dispatch the custom event
        function triggerCustomEvent() {
            var event = new CustomEvent('my-custom-event', { bubbles: true });
            document.body.dispatchEvent(event);

            // Stop polling after 5 minutes (300,000 milliseconds)
            if (Date.now() - startTime > 300000) {
                clearInterval(intervalId);
                console.log('Polling stopped after 5 minutes');
            }
        }

        // Start polling every 2 seconds
        intervalId = setInterval(triggerCustomEvent, 2000);
    });
</script>

Or stop the polling sending a http 286 response.

See this post if you are using outerHTML

dakixr avatar Jun 03 '24 08:06 dakixr