requestAnimationFrame什么时候开火?

时间:2018-04-29 13:43:50

标签: javascript requestanimationframe

似乎requestAnimationFrame仅在首次运行js代码完成后才能工作: https://jsfiddle.net/pn91zmpc/

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.Double?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.paint.LinearGradient?>
<?import javafx.scene.paint.Stop?>
<?import javafx.scene.shape.Ellipse?>
<?import javafx.scene.shape.Polygon?>
<?import javafx.scene.shape.Rectangle?>
<Pane onKeyPressed="#keyPressed" maxHeight="-Infinity" maxWidth="-Infinity" 
minHeight="-Infinity" minWidth="-Infinity"  prefHeight="600.0" 
prefWidth="800.0" xmlns="http://javafx.com/javafx/9.0.1" 
xmlns:fx="http://javafx.com/fxml/1">
<children>
  <Polygon fill="DODGERBLUE" layoutX="507.0" layoutY="587.0" rotate="180.0" 
 stroke="BLACK" strokeType="INSIDE">
    <points>
      <Double fx:value="-50.0" />
      <Double fx:value="40.0" />
      <Double fx:value="50.0" />
      <Double fx:value="40.0" />
      <Double fx:value="0.0" />
      <Double fx:value="-60.0" />
    </points>
  </Polygon>
  <Rectangle arcHeight="5.0" arcWidth="5.0" height="200.0" layoutX="-3.0" layoutY="577.0" stroke="BLACK" strokeType="INSIDE" width="809.0">
     <fill>
        <LinearGradient endX="1.0" endY="1.0">
           <stops>
              <Stop color="#4c6b33" />
              <Stop color="WHITE" offset="1.0" />
           </stops>
        </LinearGradient>
     </fill>
  </Rectangle>
  <Ellipse fx:id="Test"  fill="DODGERBLUE" layoutX="60.0" layoutY="558.0"  
  radiusX="23.0" radiusY="19.0" stroke="BLACK" strokeType="INSIDE" />
  </children>
  </Pane>

我希望看到倒计时。相反,我只看到最后的结果。 我需要更改什么来查看倒计时?

1 个答案:

答案 0 :(得分:0)

  

我需要更改什么来查看倒计时?

很多。永远不要以同步的方式尝试sleep。这将阻止一切不好的事情。相反,只需使用async / await,其中&#34;睡眠&#34;以非阻塞的方式:

 const sleep = ms => new Promise(res => setTimeout(res, ms));

 (async function() {
   for(let n = 0; n < 4; n++) {
     document.body.textContent = n;
     await sleep(1000);
   }
})();
  

requestAnimationFrame何时触发?

事件循环中的某个地方。但是当你同步阻止浏览器时,它永远不会进入事件循环,因此它不会改变输出。

PS:requestAnimationFrame,请求一个动画帧。要多次更新UI,您需要多次调用它。

相关问题