代码如何检测是否在动画帧内运行?

tru*_*ktr 5 javascript requestanimationframe

如果某个函数被传递到requestAnimationFrame(),该函数如何检测到它正在动画帧内被调用?

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."
Run Code Online (Sandbox Code Playgroud)

最后两行不应修改。我很想知道是否可以检测到这种情况,而不需要用户记住以两种不同的方式使用该功能。最终用户应该像平常一样使用该函数,而不知道我的函数检测到用例。

phu*_*uzi 0

您可以将bind您的函数传递给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."
Run Code Online (Sandbox Code Playgroud)

有关其工作原理的详细信息,请参阅Function.prototype.bind 。

更新

查看window.requestAnimationFrame的文档,回调 iesomeFunction将使用 is 进行调用DOMHighResTimeStamp

someFunction可以检测到这一点

function someFunction(domHighResTimestamp) {
  if (domHighResTimestamp) {
    console.log('Inside animation frame.')
  }
  else {
    console.log('Not inside animation frame.')
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,不能保证使用它的人someFunction不会调用它传递值。