javascriptrequestanimationframe

How can code detect if running inside an animation frame?


If some function is passed into requestAnimationFrame(), how can that function detect that it is being called inside an animation frame?

f.e.

function someFunction() {
  if (/* What goes here? */) {
    console.log('Inside animation frame.')
  }
  else {
    console.log('Not inside animation frame.')
  }
}

// The following lines should not be modified for the answer.
someFunction() // logs "Not inside animation frame."
requestAnimationFrame(someFunction) // eventually logs "Inside animation frame."

The last two lines should not be modified. I am interested to know if I can detect the situation without requiring the user to remember to use the function two different ways. The end user should just use the function like normal, without knowing that my function detects the use case.


Solution

  • You could bind your function that you pass to requestAnimationFrame.

    function someFunction(isInsideAnimationFrame, domHighResTimestamp) {
      if (isInsideAnimationFrame) {
        console.log('Inside animation frame.')
      }
      else {
        console.log('Not inside animation frame.')
      }
    }
    
    someFunction() // logs "Not inside animation frame."
    
    requestAnimationFrame(someFunction.bind(null, true)) // eventually logs "Inside animation frame."
    

    See Function.prototype.bind for details on how it works.

    UPDATE

    Looking at the docs for window.requestAnimationFrame the callback i.e. someFunction will be called with a DOMHighResTimeStamp which is .

    someFunction could detect this with

    function someFunction(domHighResTimestamp) {
      if (domHighResTimestamp) {
        console.log('Inside animation frame.')
      }
      else {
        console.log('Not inside animation frame.')
      }
    }
    

    Unfortunately there's no guarantee that whoever uses someFunction doesn't call it passing a value.