javascript - Is there a way to cancel requestAnimationFrame without a global variable? -
i'm trying cancel requestanimationframe loop, can't because each time requestanimationframe called, new timer id returned, have access return value of first call requestanimationframe.
specifically, code this, don't think entirely uncommon:
function animate(elem) { var step = function (timestamp) { //do stuff here. if (progressedtime < totaltime) { return requestanimationframe(step); //this return value seems useless. } }; return requestanimationframe(step); } //elsewhere in code, not in global namespace. var timerid = animate(elem); //a second or 2 later, before animation over. cancelanimationframe(timerid); //doesn't work! because subsequent calls requestanimationframe within step function, don't have access returned timer id in event want call cancelanimationframe.
looking @ way mozilla (and apparently others it), looks declare global variable in code (myreq in mozilla code), , assign return value of each call requestanimationframe variable can used time cancelanimationframe.
is there way without declaring global variable?
thank you.
it doesn't need global variable; needs have scope such both animate , cancel can access it. i.e. can encapsulate it. example, this:
var animation = function(elem) { var timerid; var step = function() { // ... timerid = requestanimationframe(step); }; return { start: function() { timerid = requestanimationframe(step); } cancel: function() { cancelanimationframe(timerid); } }; })(); var animation = new animation(elem); animation.start(); animation.cancel(); timerid; // error, not global. edit: don't need code every time - that's why doing programming, after all, abstract stuff repeats don't need ourselves. :)
var animation = function(step) { var timerid; var innerstep = function(timestamp) { step(timestamp); timerid = requestanimationframe(innerstep); }; return { start: function() { timerid = requestanimationframe(innerstep); } cancel: function() { cancelanimationframe(timerid); } }; })(); var animation1 = new animation(function(timestamp) { // elem1 }); var animation2 = new animation(function(timestamp) { // elem2 });
Comments
Post a Comment