stackoverflow stackoverflow - 8 months ago 35
Javascript Question

JS How to control an anonymous function


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?



<div id="seventyfive" style="position:absolute; font-size:10px; font-weight:bold">
<img src="" style="width:50px"/>


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

var on = true;

on = !on;


// Start/Stop Pulse function


JSFiddle Example JSFiddle Example


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

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

@keyframes pulse {
  0% {
    transform: none;
  100% {
    transform: scale(1.2);
    opacity: 0.3;
<script src=""></script>
<div id="seventyfive" class="heart" style="position:absolute; font-size:10px; font-weight:bold">
  <img src="" style="width:50px" />

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.