deterministic-injection.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * @author munrocket / https://twitter.com/munrocket_twit
  3. */
  4. ( function () {
  5. /* Deterministic random */
  6. window.Math._random = window.Math.random;
  7. let seed = Math.PI / 4;
  8. window.Math.random = function () {
  9. const x = Math.sin( seed ++ ) * 10000;
  10. return x - Math.floor( x );
  11. };
  12. /* Deterministic timer */
  13. window.performance._now = performance.now;
  14. let frameId = 0;
  15. const now = () => frameId * 16;
  16. window.Date.now = now;
  17. window.Date.prototype.getTime = now;
  18. window.performance.now = now;
  19. /* Deterministic RAF */
  20. const RAF = window.requestAnimationFrame;
  21. window._renderStarted = false;
  22. window._renderFinished = false;
  23. const maxFrameId = 2;
  24. window.requestAnimationFrame = function ( cb ) {
  25. if ( ! _renderStarted ) {
  26. setTimeout( function () {
  27. requestAnimationFrame( cb );
  28. }, 50 );
  29. } else {
  30. RAF( function () {
  31. if ( frameId ++ < maxFrameId ) {
  32. cb( now() );
  33. } else {
  34. _renderFinished = true;
  35. }
  36. } );
  37. }
  38. };
  39. /* Semi-determitistic video */
  40. const play = HTMLVideoElement.prototype.play;
  41. HTMLVideoElement.prototype.play = async function () {
  42. play.call( this );
  43. this.addEventListener( 'timeupdate', () => this.pause() );
  44. function renew() {
  45. this.load();
  46. play.call( this );
  47. RAF( renew );
  48. }
  49. RAF( renew );
  50. };
  51. /* Additional variable for ~5 examples */
  52. window.TESTING = true;
  53. }() );
粤ICP备19079148号