Best JavaScript code snippet using playwright-internal
TimerExample.js
Source:TimerExample.js  
1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @format8 * @flow9 */10'use strict';11const RNTesterButton = require('../../components/RNTesterButton');12const React = require('react');13const {Alert, Platform, ToastAndroid, Text, View} = require('react-native');14function burnCPU(milliseconds) {15  const start = global.performance.now();16  while (global.performance.now() < start + milliseconds) {}17}18type RequestIdleCallbackTesterProps = $ReadOnly<{||}>;19type RequestIdleCallbackTesterState = {|message: string|};20class RequestIdleCallbackTester extends React.Component<21  RequestIdleCallbackTesterProps,22  RequestIdleCallbackTesterState,23> {24  state = {25    message: '-',26  };27  _idleTimer: ?IdleCallbackID = null;28  _iters = 0;29  componentWillUnmount() {30    if (this._idleTimer != null) {31      cancelIdleCallback(this._idleTimer);32      this._idleTimer = null;33    }34  }35  render() {36    return (37      <View>38        <RNTesterButton onPress={this._run.bind(this, false)}>39          Run requestIdleCallback40        </RNTesterButton>41        <RNTesterButton onPress={this._run.bind(this, true)}>42          Burn CPU inside of requestIdleCallback43        </RNTesterButton>44        <RNTesterButton onPress={this._runWithTimeout}>45          Run requestIdleCallback with timeout option46        </RNTesterButton>47        <RNTesterButton onPress={this._runBackground}>48          Run background task49        </RNTesterButton>50        <RNTesterButton onPress={this._stopBackground}>51          Stop background task52        </RNTesterButton>53        <Text>{this.state.message}</Text>54      </View>55    );56  }57  _run(shouldBurnCPU: boolean) {58    if (this._idleTimer != null) {59      cancelIdleCallback(this._idleTimer);60      this._idleTimer = null;61    }62    this._idleTimer = requestIdleCallback(deadline => {63      let message = '';64      if (shouldBurnCPU) {65        burnCPU(10);66        message = 'Burned CPU for 10ms,';67      }68      this.setState({69        message: `${message} ${deadline.timeRemaining()}ms remaining in frame`,70      });71    });72  }73  _runWithTimeout = () => {74    if (this._idleTimer != null) {75      cancelIdleCallback(this._idleTimer);76      this._idleTimer = null;77    }78    this._idleTimer = requestIdleCallback(79      deadline => {80        this.setState({81          message: `${deadline.timeRemaining()}ms remaining in frame, it did timeout: ${82            deadline.didTimeout ? 'yes' : 'no'83          }`,84        });85      },86      {timeout: 100},87    );88    burnCPU(100);89  };90  _runBackground = () => {91    if (this._idleTimer != null) {92      cancelIdleCallback(this._idleTimer);93      this._idleTimer = null;94    }95    const handler = deadline => {96      while (deadline.timeRemaining() > 5) {97        burnCPU(5);98        this.setState({99          message: `Burned CPU for 5ms ${this100            ._iters++} times, ${deadline.timeRemaining()}ms remaining in frame`,101        });102      }103      this._idleTimer = requestIdleCallback(handler);104    };105    this._idleTimer = requestIdleCallback(handler);106  };107  _stopBackground = () => {108    this._iters = 0;109    if (this._idleTimer != null) {110      cancelIdleCallback(this._idleTimer);111      this._idleTimer = null;112    }113  };114}115type TimerTesterProps = $ReadOnly<{|116  dt?: number,117  type: string,118|}>;119class TimerTester extends React.Component<TimerTesterProps> {120  _ii = 0;121  _iters = 0;122  _start = 0;123  _timerId: ?TimeoutID = null;124  _rafId: ?AnimationFrameID = null;125  _intervalId: ?IntervalID = null;126  _immediateId: ?Object = null;127  _timerFn: ?() => any = null;128  render() {129    const args =130      'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : '');131    return (132      <RNTesterButton onPress={this._run}>133        Measure: {this.props.type}({args}) - {this._ii || 0}134      </RNTesterButton>135    );136  }137  componentWillUnmount() {138    if (this._timerId != null) {139      clearTimeout(this._timerId);140      this._timerId = null;141    }142    if (this._rafId != null) {143      cancelAnimationFrame(this._rafId);144      this._rafId = null;145    }146    if (this._immediateId != null) {147      clearImmediate(this._immediateId);148      this._immediateId = null;149    }150    if (this._intervalId != null) {151      clearInterval(this._intervalId);152      this._intervalId = null;153    }154  }155  _run = () => {156    if (!this._start) {157      const d = new Date();158      this._start = d.getTime();159      this._iters = 100;160      this._ii = 0;161      if (this.props.type === 'setTimeout') {162        if (this.props.dt !== undefined && this.props.dt < 1) {163          this._iters = 5000;164        } else if (this.props.dt !== undefined && this.props.dt > 20) {165          this._iters = 10;166        }167        this._timerFn = () => {168          this._timerId = setTimeout(this._run, this.props.dt);169        };170      } else if (this.props.type === 'requestAnimationFrame') {171        this._timerFn = () => {172          this._rafId = requestAnimationFrame(this._run);173        };174      } else if (this.props.type === 'setImmediate') {175        this._iters = 5000;176        this._timerFn = () => {177          this._immediateId = setImmediate(this._run);178        };179      } else if (this.props.type === 'setInterval') {180        this._iters = 30; // Only used for forceUpdate periodicity181        this._timerFn = null;182        this._intervalId = setInterval(this._run, this.props.dt);183      }184    }185    if (this._ii >= this._iters && this._intervalId == null) {186      const d = new Date();187      const e = d.getTime() - this._start;188      const msg =189        'Finished ' +190        this._ii +191        ' ' +192        this.props.type +193        ' calls.\n' +194        'Elapsed time: ' +195        e +196        ' ms\n' +197        e / this._ii +198        ' ms / iter';199      console.log(msg);200      if (Platform.OS === 'ios') {201        Alert.alert(msg);202      } else if (Platform.OS === 'android') {203        ToastAndroid.show(msg, ToastAndroid.SHORT);204      }205      this._start = 0;206      this.forceUpdate(() => {207        this._ii = 0;208      });209      return;210    }211    this._ii++;212    // Only re-render occasionally so we don't slow down timers.213    if (this._ii % (this._iters / 5) === 0) {214      this.forceUpdate();215    }216    if (this._timerFn) {217      this._timerId = this._timerFn();218    }219  };220  clear = () => {221    if (this._intervalId != null) {222      clearInterval(this._intervalId);223      // Configure things so we can do a final run to update UI and reset state.224      this._intervalId = null;225      this._iters = this._ii;226      this._run();227    }228  };229}230exports.framework = 'React';231exports.title = 'Timers';232exports.category = 'UI';233exports.description = 'A demonstration of Timers in React Native.';234exports.examples = [235  {236    title: 'this.setTimeout(fn, t)',237    description: ('Execute function fn t milliseconds in the future.  If ' +238      't === 0, it will be enqueued immediately in the next event loop.  ' +239      'Larger values will fire on the closest frame.': string),240    render: function(): React.Node {241      return (242        <View>243          <TimerTester type="setTimeout" dt={0} />244          <TimerTester type="setTimeout" dt={1} />245          <TimerTester type="setTimeout" dt={100} />246        </View>247      );248    },249  },250  {251    title: 'this.requestAnimationFrame(fn)',252    description: 'Execute function fn on the next frame.',253    render: function(): React.Node {254      return (255        <View>256          <TimerTester type="requestAnimationFrame" />257        </View>258      );259    },260  },261  {262    title: 'this.requestIdleCallback(fn)',263    description: 'Execute function fn on the next JS frame that has idle time',264    render: function(): React.Node {265      return (266        <View>267          <RequestIdleCallbackTester />268        </View>269      );270    },271  },272  {273    title: 'this.setImmediate(fn)',274    description: 'Execute function fn at the end of the current JS event loop.',275    render: function(): React.Node {276      return (277        <View>278          <TimerTester type="setImmediate" />279        </View>280      );281    },282  },283  {284    title: 'this.setInterval(fn, t)',285    description: ('Execute function fn every t milliseconds until cancelled ' +286      'or component is unmounted.': string),287    render: function(): React.Node {288      type IntervalExampleProps = $ReadOnly<{||}>;289      type IntervalExampleState = {|290        showTimer: boolean,291      |};292      class IntervalExample extends React.Component<293        IntervalExampleProps,294        IntervalExampleState,295      > {296        state = {297          showTimer: true,298        };299        _timerTester: ?React.ElementRef<typeof TimerTester>;300        render() {301          return (302            <View>303              {this.state.showTimer && this._renderTimer()}304              <RNTesterButton onPress={this._toggleTimer}>305                {this.state.showTimer ? 'Unmount timer' : 'Mount new timer'}306              </RNTesterButton>307            </View>308          );309        }310        _renderTimer = () => {311          return (312            <View>313              <TimerTester314                ref={ref => (this._timerTester = ref)}315                dt={25}316                type="setInterval"317              />318              <RNTesterButton319                onPress={() => this._timerTester && this._timerTester.clear()}>320                Clear interval321              </RNTesterButton>322            </View>323          );324        };325        _toggleTimer = () => {326          this.setState({showTimer: !this.state.showTimer});327        };328      }329      return <IntervalExample />;330    },331  },...index.js
Source:index.js  
1"use strict";2exports.__esModule = true;3exports.default = void 0;4var _isPlainObj = _interopRequireDefault(require("is-plain-obj"));5var _parse = _interopRequireDefault(require("./parse"));6var _export = _interopRequireDefault(require("../util/export"));7var _getTypes = _interopRequireDefault(require("../types/getTypes"));8var _getModelFieldLimit = _interopRequireDefault(require("../util/getModelFieldLimit"));9var _runWithTimeout = _interopRequireDefault(require("../util/runWithTimeout"));10function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }11class Query {12  constructor(obj, options = {}) {13    this.update = fn => {14      if ((0, _isPlainObj.default)(fn)) return this.update(v => ({ ...v,15        ...fn16      }));17      if (typeof fn !== 'function') throw new Error('Missing update function!'); // update instance query18      const newInstanceValue = fn(this._parsed);19      if (!newInstanceValue || typeof newInstanceValue !== 'object') throw new Error('Invalid update function! Must return an object.');20      this._parsed = newInstanceValue; // update non-instance query21      const newCollectionValue = fn(this._parsedCollection);22      if (!newCollectionValue || typeof newCollectionValue !== 'object') throw new Error('Invalid update function! Must return an object.');23      this._parsedCollection = newCollectionValue;24      return this;25    };26    this.constrain = ({27      defaultLimit,28      maxLimit,29      attributes,30      where31    } = {}) => {32      if (where && !Array.isArray(where)) throw new Error('Invalid where array!');33      if (attributes && !Array.isArray(attributes)) throw new Error('Invalid attributes array!');34      return this.update(v => {35        const limit = v.limit || defaultLimit;36        return { ...v,37          attributes: attributes || v.attributes,38          where: where ? [...v.where, ...where] : v.where,39          limit: maxLimit ? limit ? Math.min(limit, maxLimit) : maxLimit : limit40        };41      });42    };43    this.value = ({44      instanceQuery = true45    } = {}) => instanceQuery ? this._parsed : this._parsedCollection;46    this.toJSON = () => this.input;47    this.getOutputSchema = () => {48      let fieldLimit = this.options.fieldLimit || (0, _getModelFieldLimit.default)(this.options.model);49      if (this.input.exclusions) {50        fieldLimit = fieldLimit.filter(i => !this.input.exclusions.includes(i.field));51      }52      return fieldLimit.reduce((acc, f) => {53        acc[f.field] = (0, _getTypes.default)({54          field: f.field55        }, this.options)[0];56        return acc;57      }, {});58    };59    this.execute = async ({60      raw = false,61      useMaster,62      debug = this.options.model.sequelize.options.logging,63      timeout64    } = {}) => {65      const fn = this.options.count !== false ? 'findAndCountAll' : 'findAll';66      const exec = transaction => this.options.model[fn]({67        raw,68        useMaster,69        logging: debug,70        transaction,71        ...this.value()72      });73      if (!timeout) return exec();74      return (0, _runWithTimeout.default)(exec, {75        sequelize: this.options.model.sequelize,76        timeout77      });78    };79    this.executeStream = async ({80      onError,81      format,82      tupleFraction,83      transform,84      useMaster,85      debug = this.options.model.sequelize.options.logging,86      timeout,87      finishTimeout88    } = {}) => (0, _export.default)({89      timeout,90      finishTimeout,91      useMaster,92      tupleFraction,93      format,94      transform,95      onError,96      debug,97      model: this.options.model,98      value: this.value()99    });100    this.count = async ({101      useMaster,102      timeout,103      debug = this.options.model.sequelize.options.logging104    } = {}) => {105      const exec = transaction => this.options.model.count({106        useMaster,107        transaction,108        logging: debug,109        ...this.value()110      });111      if (!timeout) return exec();112      return (0, _runWithTimeout.default)(exec, {113        sequelize: this.options.model.sequelize,114        timeout115      });116    };117    this.destroy = async ({118      debug = this.options.model.sequelize.options.logging,119      timeout120    } = {}) => {121      const exec = transaction => this.options.model.destroy({122        logging: debug,123        transaction,124        ...this.value({125          instanceQuery: false126        })127      });128      if (!timeout) return exec();129      return (0, _runWithTimeout.default)(exec, {130        sequelize: this.options.model.sequelize,131        timeout132      });133    };134    if (!obj) throw new Error('Missing query!');135    if (!options.model || !options.model.rawAttributes) throw new Error('Missing model!');136    if (options.fieldLimit && !Array.isArray(options.fieldLimit)) throw new Error('Invalid fieldLimit!');137    this.input = obj;138    this.options = options;139    this._parsed = (0, _parse.default)(obj, options);140    this._parsedCollection = (0, _parse.default)(obj, { ...options,141      instanceQuery: false142    });143  }144}145exports.default = Query;...queue.js
Source:queue.js  
...38    this.runTask(nextTask);39    // call next to run multiple tasks concurrently40    this.next();41  }42  _runWithTimeout(task) {43    return new Promise((resolve, reject)=> {44      const timer = setTimeout(()=> {45        const err = new Error('Timeout');46        err.code = 'ETIMEDOUT';47        reject(err);48      }, this.timeout);49      Promise.resolve()50        .then(task)51        .then(resolve)52        .catch(reject)53        .finally(()=> clearTimeout(timer));54    });55  }56  async runTask(task) {57    let result, error;58    this.emitter.emit('will-run', task);59    try {60      result = await (this.timeout? this._runWithTimeout(task): task());61    } catch(err) {62      error = err;63    }64    // ignore task if the queue has been cleared65    if(!this.runningTasks.includes(task)) return;66    // remove task from running task list67    this.runningTasks.splice(this.runningTasks.indexOf(task), 1);68    // notify failure or success69    if(error) {70      this.emitter.emit('did-fail', { task, error });71    } else {72      this.emitter.emit('did-run', { task , result });73    }74    // run next task...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
