stackoverflow stackoverflow - 3 months ago 12
Javascript Question

JS How to control an anonymous function

Scenario:

I have a function that I want to automatically invoke. But on a mouse click I want this function to stop. How to control an anonymous function in JS?

Example

HTML

<div id="seventyfive" style="position:absolute; font-size:10px; font-weight:bold">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Heart_coraz%C3%B3n.svg/200px-Heart_coraz%C3%B3n.svg.png" style="width:50px"/>
</div>


JS

(function pulse(back) {
$('#seventyfive').animate(
{
'font-size': (back) ? '10px' : '15px',
opacity: (back) ? 0.3 : 1
}, 600, function(){pulse(!back)});
$('#seventyfive img').animate(
{
'width': (back) ? '50px' : '40px'
}, 600);
})(false);

var on = true;
$("#seventyfive").click(function(){

on = !on;

if(on){

// Start/Stop Pulse function
}

});


JSFiddle Example JSFiddle Example

Answer

You can benefit from hardware acceleration by using CSS, which massively improves performance.

$("#seventyfive").click(function() {
  $(this).toggleClass("pulsing");
});
.heart.pulsing img {
  animation: pulse 600ms ease infinite alternate;
}

@keyframes pulse {
  0% {
    transform: none;
  }
  100% {
    transform: scale(1.2);
    opacity: 0.3;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<div id="seventyfive" class="heart" style="position:absolute; font-size:10px; font-weight:bold">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Heart_coraz%C3%B3n.svg/200px-Heart_coraz%C3%B3n.svg.png" style="width:50px" />
</div>

With this, just apply the pulsing class to #seventyfive, and the heart will pulse. Notice that this animates opacity and transform, not font-size, to avoid triggering the browser to perform a re-layout.

Comments