The animation function is implemented on setTimeout () through recursion. How can I stop its execution from another function?

animate: function(itm, prop, unit, fromVal, toVal, time, callback){ slider.sett.progress = true; var fps = .06; var frame = 0; var direction = fromVal < toVal ? true : false; var distance = direction ? (toVal - fromVal) : (fromVal - toVal); var delta = distance / time / fps; var handle = setTimeout(function run() { frame++; var step = delta * frame; var value = direction ? (fromVal + step) : (fromVal - step) ; itm.style[prop] = value + unit; if (direction && value < toVal || !direction && value > toVal) { setTimeout(run, 1 / fps); } else { itm.style[prop] = value + unit; slider.sett.progress = false; callback ? callback() : false; } }); }, 

    2 answers 2

     animate: function(itm, prop, unit, fromVal, toVal, time, callback){ ... var timeoutHolder = {}; timeoutHolder.handle = setTimeout(function run() { ... if (direction && value < toVal || !direction && value > toVal) { timeoutHolder.handle = setTimeout(run, 1 / fps); } else { ... } }); return timeoutHolder; }, var timeout = a.animate(...); clearTimeout(timeout.handle); 

    Note the assignment of timeoutHolder.handle on repeated calls to setTimeout .

      You can clear it with:

       clearTimeout(handle); 

      UPD

       var handle; var obj = { animate: function(itm, prop, unit, fromVal, toVal, time, callback){ slider.sett.progress = true; var fps = .06; var frame = 0; var direction = fromVal < toVal ? true : false; var distance = direction ? (toVal - fromVal) : (fromVal - toVal); var delta = distance / time / fps; handle = setTimeout(function run() { frame++; var step = delta * frame; var value = direction ? (fromVal + step) : (fromVal - step) ; itm.style[prop] = value + unit; if (direction && value < toVal || !direction && value > toVal) { setTimeout(run, 1 / fps); } else { itm.style[prop] = value + unit; slider.sett.progress = false; callback ? callback() : false; } }); } } if( handle ) clearTimeout(handle); 

      Note! The timer inside is declared without var!

      • if I do it from another function, I get the Uncaught ReferenceError: handle is not defined - Joe
      • ))) At the beginning of the script, declare a var handle , and in the function itself use no var . - borodatych
      • @Joe so tell me what to clean - Jean-Claude
      • @Joe, added under upd , wrote about what a little higher. - borodatych