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
Use nested timeouts.
$timeout(function () {
$('#reportingLoopPage').removeClass('assertive-bg');
$timeout(function () {
$('#reportingLoopPage').addClass('positive-bg');
}, 5000);
}, 5000);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With