Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change element's CSS for 5 seconds, but persist if next event is still within 5

I'm building an app with beacons. Whenever an event is fired I want to change the background color to red for 5 seconds, then back to blue after the 5 seconds is up. Without complication this is very easy I just use a $timeout and voila.

My problem is that if the event if fired again within that same 5 seconds, I want to extend the length that the background is red to be 5 seconds from then.

My current code sort of does the job but keeps flickering whenever the original 5 seconds is up.

            $('#reportingLoopPage').removeClass('positive-bg');
            $('#reportingLoopPage').addClass('assertive-bg');

            $timeout(function () {
                $('#reportingLoopPage').removeClass('assertive-bg');
                $('#reportingLoopPage').addClass('positive-bg');
            }, 5000);

How can I persist a change for a duration of 5 seconds, resetting that duration whenever the event is fired again?

I'm happy to use any combo of JS, Angular, and JQuery

like image 387
Joshua Ohana Avatar asked Dec 05 '25 05:12

Joshua Ohana


2 Answers

Use nested timeouts.

$timeout(function () {
    $('#reportingLoopPage').removeClass('assertive-bg');
    $timeout(function () {
        $('#reportingLoopPage').addClass('positive-bg');
    }, 5000);
}, 5000);
like image 153
Praveen Kumar Purushothaman Avatar answered Dec 07 '25 21:12

Praveen Kumar Purushothaman


My problem is that if the event if fired again within that same 5 seconds, I want to extend the length that the background is red to be 5 seconds from then.

You could use $timeout.cancel(promiseVariable) to cancel the current timer and create a new one.

var promise;

//More code...

$('#reportingLoopPage').removeClass('positive-bg');
$('#reportingLoopPage').addClass('assertive-bg');

$timeout.cancel(promise);

promise = $timeout(function () {
    $('#reportingLoopPage').removeClass('assertive-bg');
    $('#reportingLoopPage').addClass('positive-bg');
}, 5000);
like image 29
Walter Chapilliquen - wZVanG Avatar answered Dec 07 '25 22:12

Walter Chapilliquen - wZVanG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!