Change the CSS element for 5 seconds, but save if the next event is still within 5
I am creating an app with beacons. Whenever the event fires, I want to change the background color to red for 5 seconds and then back to blue after 5 seconds. It's very easy without complications, I just use $ timeout and voila.
My problem is that if the event, if it fires inside again in the same 5 seconds, I want to increase the background length so that red is 5 seconds.
My current type of code does the job, but keeps flickering whenever the original 5 seconds.
$('#reportingLoopPage').removeClass('positive-bg');
$('#reportingLoopPage').addClass('assertive-bg');
$timeout(function () {
$('#reportingLoopPage').removeClass('assertive-bg');
$('#reportingLoopPage').addClass('positive-bg');
}, 5000);
How can I keep the changes for 5 seconds, resetting this duration whenever the event is fired again?
I am happy to use any combination of JS, Angular and JQuery
source to share
My problem is that if the event, if fired again within the same 5 seconds, I want to extend the length at which the red background will be 5 seconds.
You can 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);
source to share
It is .delay()
also possible to use.
The .delay () method is best for delaying between jQuery queued after effects. Because it is limited - it does not, for example, offer a way to undo the delay..delay () is not a replacement for the native JavaScript setTimeout, which might be more appropriate for certain use cases.
$('#reportingLoopPage').delay(5000).removeClass('assertive-bg');
$('#reportingLoopPage').delay(10000).addClass('positive-bg');
source to share
var myTimeout;
function myFunction()
{
$('#reportingLoopPage').removeClass('positive-bg');
$('#reportingLoopPage').addClass('assertive-bg');
clearTimeout(myTimeout);
myTimeout = setTimeout(function () {
$('#reportingLoopPage').removeClass('assertive-bg');
$('#reportingLoopPage').addClass('positive-bg');
}, 5000);
}
source to share