How to use throttle method in Webdriverio

Best JavaScript code snippet using webdriverio-monorepo

throttle_tests.js

Source:throttle_tests.js Github

copy

Full Screen

...33 await this.start({34 hasTimeControl: true,35 });36 let hasInvokedFunc = false;37 const throttledFunc = throttle(38 this.env,39 () => {40 hasInvokedFunc = true;41 return 'func_result';42 },43 044 );45 this.throttles.push(throttledFunc);46 assert.notOk(47 hasInvokedFunc,48 "func should not have been invoked on immediate throttle initialization"49 );50 await this.env.testUtils.advanceTime(0);51 assert.notOk(52 hasInvokedFunc,53 "func should not have been invoked from throttle initialization after 0ms"54 );55 throttledFunc().then(res => {56 assert.step('throttle_observed_invoke');57 assert.strictEqual(58 res,59 'func_result',60 "throttle call return should forward result of inner func"61 );62 });63 await nextTick();64 assert.ok(65 hasInvokedFunc,66 "func should have been immediately invoked on first throttle call"67 );68 assert.verifySteps(69 ['throttle_observed_invoke'],70 "throttle should have observed invoked on first throttle call"71 );72});73QUnit.test('2nd (throttled) call', async function (assert) {74 assert.expect(8);75 await this.start({76 hasTimeControl: true,77 });78 let funcCalledAmount = 0;79 const throttledFunc = throttle(80 this.env,81 () => {82 funcCalledAmount++;83 return `func_result_${funcCalledAmount}`;84 },85 100086 );87 this.throttles.push(throttledFunc);88 throttledFunc().then(result => {89 assert.step('throttle_observed_invoke_1');90 assert.strictEqual(91 result,92 'func_result_1',93 "throttle call return should forward result of inner func 1"94 );95 });96 await nextTick();97 assert.verifySteps(98 ['throttle_observed_invoke_1'],99 "inner function of throttle should have been invoked on 1st call (immediate return)"100 );101 throttledFunc().then(res => {102 assert.step('throttle_observed_invoke_2');103 assert.strictEqual(104 res,105 'func_result_2',106 "throttle call return should forward result of inner func 2"107 );108 });109 await nextTick();110 assert.verifySteps(111 [],112 "inner function of throttle should not have been immediately invoked after 2nd call immediately after 1st call (throttled with 1s internal clock)"113 );114 await this.env.testUtils.advanceTime(999);115 assert.verifySteps(116 [],117 "inner function of throttle should not have been invoked after 999ms of 2nd call (throttled with 1s internal clock)"118 );119 await this.env.testUtils.advanceTime(1);120 assert.verifySteps(121 ['throttle_observed_invoke_2'],122 "inner function of throttle should not have been invoked after 1s of 2nd call (throttled with 1s internal clock)"123 );124});125QUnit.test('throttled call reinvocation', async function (assert) {126 assert.expect(11);127 await this.start({128 hasTimeControl: true,129 });130 let funcCalledAmount = 0;131 const throttledFunc = throttle(132 this.env,133 () => {134 funcCalledAmount++;135 return `func_result_${funcCalledAmount}`;136 },137 1000,138 { silentCancelationErrors: false }139 );140 this.throttles.push(throttledFunc);141 throttledFunc().then(result => {142 assert.step('throttle_observed_invoke_1');143 assert.strictEqual(144 result,145 'func_result_1',146 "throttle call return should forward result of inner func 1"147 );148 });149 await nextTick();150 assert.verifySteps(151 ['throttle_observed_invoke_1'],152 "inner function of throttle should have been invoked on 1st call (immediate return)"153 );154 throttledFunc()155 .then(() => {156 throw new Error("2nd throttle call should not be resolved (should have been canceled by reinvocation)");157 })158 .catch(error => {159 assert.ok(160 error instanceof ThrottleReinvokedError,161 "Should generate a Throttle reinvoked error (from another throttle function call)"162 );163 assert.step('throttle_reinvoked_1');164 });165 await nextTick();166 assert.verifySteps(167 [],168 "inner function of throttle should not have been immediately invoked after 2nd call immediately after 1st call (throttled with 1s internal clock)"169 );170 await this.env.testUtils.advanceTime(999);171 assert.verifySteps(172 [],173 "inner function of throttle should not have been invoked after 999ms of 2nd call (throttled with 1s internal clock)"174 );175 throttledFunc()176 .then(result => {177 assert.step('throttle_observed_invoke_2');178 assert.strictEqual(179 result,180 'func_result_2',181 "throttle call return should forward result of inner func 2"182 );183 });184 await nextTick();185 assert.verifySteps(186 ['throttle_reinvoked_1'],187 "2nd throttle call should have been canceled from 3rd throttle call (reinvoked before cooling down phase has ended)"188 );189 await this.env.testUtils.advanceTime(1);190 assert.verifySteps(191 ['throttle_observed_invoke_2'],192 "inner function of throttle should have been invoked after 1s of 1st call (throttled with 1s internal clock, 3rd throttle call re-use timer of 2nd throttle call)"193 );194});195QUnit.test('flush throttled call', async function (assert) {196 assert.expect(9);197 await this.start({198 hasTimeControl: true,199 });200 const throttledFunc = throttle(201 this.env,202 () => {},203 1000,204 );205 this.throttles.push(throttledFunc);206 throttledFunc().then(() => assert.step('throttle_observed_invoke_1'));207 await nextTick();208 assert.verifySteps(209 ['throttle_observed_invoke_1'],210 "inner function of throttle should have been invoked on 1st call (immediate return)"211 );212 throttledFunc().then(() => assert.step('throttle_observed_invoke_2'));213 await nextTick();214 assert.verifySteps(215 [],216 "inner function of throttle should not have been immediately invoked after 2nd call immediately after 1st call (throttled with 1s internal clock)"217 );218 await this.env.testUtils.advanceTime(10);219 assert.verifySteps(220 [],221 "inner function of throttle should not have been invoked after 10ms of 2nd call (throttled with 1s internal clock)"222 );223 throttledFunc.flush();224 await nextTick();225 assert.verifySteps(226 ['throttle_observed_invoke_2'],227 "inner function of throttle should have been invoked from 2nd call after flush"228 );229 throttledFunc().then(() => assert.step('throttle_observed_invoke_3'));230 await nextTick();231 await this.env.testUtils.advanceTime(999);232 assert.verifySteps(233 [],234 "inner function of throttle should not have been invoked after 999ms of 3rd call (throttled with 1s internal clock)"235 );236 await this.env.testUtils.advanceTime(1);237 assert.verifySteps(238 ['throttle_observed_invoke_3'],239 "inner function of throttle should not have been invoked after 999ms of 3rd call (throttled with 1s internal clock)"240 );241});242QUnit.test('cancel throttled call', async function (assert) {243 assert.expect(10);244 await this.start({245 hasTimeControl: true,246 });247 const throttledFunc = throttle(248 this.env,249 () => {},250 1000,251 { silentCancelationErrors: false }252 );253 this.throttles.push(throttledFunc);254 throttledFunc().then(() => assert.step('throttle_observed_invoke_1'));255 await nextTick();256 assert.verifySteps(257 ['throttle_observed_invoke_1'],258 "inner function of throttle should have been invoked on 1st call (immediate return)"259 );260 throttledFunc()261 .then(() => {262 throw new Error("2nd throttle call should not be resolved (should have been canceled)");263 })264 .catch(error => {265 assert.ok(266 error instanceof ThrottleCanceledError,267 "Should generate a Throttle canceled error (from `.cancel()`)"268 );269 assert.step('throttle_canceled');270 });271 await nextTick();272 assert.verifySteps(273 [],274 "inner function of throttle should not have been immediately invoked after 2nd call immediately after 1st call (throttled with 1s internal clock)"275 );276 await this.env.testUtils.advanceTime(500);277 assert.verifySteps(278 [],279 "inner function of throttle should not have been invoked after 500ms of 2nd call (throttled with 1s internal clock)"280 );281 throttledFunc.cancel();282 await nextTick();283 assert.verifySteps(284 ['throttle_canceled'],285 "2nd throttle function call should have been canceled"286 );287 throttledFunc().then(() => assert.step('throttle_observed_invoke_3'));288 await nextTick();289 assert.verifySteps(290 [],291 "3rd throttle function call should not have invoked inner function yet (cancel reuses inner clock of throttle)"292 );293 await this.env.testUtils.advanceTime(500);294 assert.verifySteps(295 ['throttle_observed_invoke_3'],296 "3rd throttle function call should have invoke inner function after 500ms (cancel reuses inner clock of throttle which was at 500ms in, throttle set at 1ms)"297 );298});299QUnit.test('clear throttled call', async function (assert) {300 assert.expect(9);301 await this.start({302 hasTimeControl: true,303 });304 const throttledFunc = throttle(305 this.env,306 () => {},307 1000,308 { silentCancelationErrors: false }309 );310 this.throttles.push(throttledFunc);311 throttledFunc().then(() => assert.step('throttle_observed_invoke_1'));312 await nextTick();313 assert.verifySteps(314 ['throttle_observed_invoke_1'],315 "inner function of throttle should have been invoked on 1st call (immediate return)"316 );317 throttledFunc()318 .then(() => {...

Full Screen

Full Screen

ThrottleInfoReport.js

Source:ThrottleInfoReport.js Github

copy

Full Screen

1// Auto-generated. Do not edit!2// (in-package dbw_mkz_msgs.msg)3"use strict";4const _serializer = _ros_msg_utils.Serialize;5const _arraySerializer = _serializer.Array;6const _deserializer = _ros_msg_utils.Deserialize;7const _arrayDeserializer = _deserializer.Array;8const _finder = _ros_msg_utils.Find;9const _getByteLength = _ros_msg_utils.getByteLength;10let QualityFactor = require('./QualityFactor.js');11let GearNum = require('./GearNum.js');12let std_msgs = _finder('std_msgs');13//-----------------------------------------------------------14class ThrottleInfoReport {15 constructor(initObj={}) {16 if (initObj === null) {17 // initObj === null is a special case for deserialization where we don't initialize fields18 this.header = null;19 this.throttle_pc = null;20 this.throttle_rate = null;21 this.throttle_pedal_qf = null;22 this.engine_rpm = null;23 this.gear_num = null;24 }25 else {26 if (initObj.hasOwnProperty('header')) {27 this.header = initObj.header28 }29 else {30 this.header = new std_msgs.msg.Header();31 }32 if (initObj.hasOwnProperty('throttle_pc')) {33 this.throttle_pc = initObj.throttle_pc34 }35 else {36 this.throttle_pc = 0.0;37 }38 if (initObj.hasOwnProperty('throttle_rate')) {39 this.throttle_rate = initObj.throttle_rate40 }41 else {42 this.throttle_rate = 0.0;43 }44 if (initObj.hasOwnProperty('throttle_pedal_qf')) {45 this.throttle_pedal_qf = initObj.throttle_pedal_qf46 }47 else {48 this.throttle_pedal_qf = new QualityFactor();49 }50 if (initObj.hasOwnProperty('engine_rpm')) {51 this.engine_rpm = initObj.engine_rpm52 }53 else {54 this.engine_rpm = 0.0;55 }56 if (initObj.hasOwnProperty('gear_num')) {57 this.gear_num = initObj.gear_num58 }59 else {60 this.gear_num = new GearNum();61 }62 }63 }64 static serialize(obj, buffer, bufferOffset) {65 // Serializes a message object of type ThrottleInfoReport66 // Serialize message field [header]67 bufferOffset = std_msgs.msg.Header.serialize(obj.header, buffer, bufferOffset);68 // Serialize message field [throttle_pc]69 bufferOffset = _serializer.float32(obj.throttle_pc, buffer, bufferOffset);70 // Serialize message field [throttle_rate]71 bufferOffset = _serializer.float32(obj.throttle_rate, buffer, bufferOffset);72 // Serialize message field [throttle_pedal_qf]73 bufferOffset = QualityFactor.serialize(obj.throttle_pedal_qf, buffer, bufferOffset);74 // Serialize message field [engine_rpm]75 bufferOffset = _serializer.float32(obj.engine_rpm, buffer, bufferOffset);76 // Serialize message field [gear_num]77 bufferOffset = GearNum.serialize(obj.gear_num, buffer, bufferOffset);78 return bufferOffset;79 }80 static deserialize(buffer, bufferOffset=[0]) {81 //deserializes a message object of type ThrottleInfoReport82 let len;83 let data = new ThrottleInfoReport(null);84 // Deserialize message field [header]85 data.header = std_msgs.msg.Header.deserialize(buffer, bufferOffset);86 // Deserialize message field [throttle_pc]87 data.throttle_pc = _deserializer.float32(buffer, bufferOffset);88 // Deserialize message field [throttle_rate]89 data.throttle_rate = _deserializer.float32(buffer, bufferOffset);90 // Deserialize message field [throttle_pedal_qf]91 data.throttle_pedal_qf = QualityFactor.deserialize(buffer, bufferOffset);92 // Deserialize message field [engine_rpm]93 data.engine_rpm = _deserializer.float32(buffer, bufferOffset);94 // Deserialize message field [gear_num]95 data.gear_num = GearNum.deserialize(buffer, bufferOffset);96 return data;97 }98 static getMessageSize(object) {99 let length = 0;100 length += std_msgs.msg.Header.getMessageSize(object.header);101 return length + 14;102 }103 static datatype() {104 // Returns string type for a message object105 return 'dbw_mkz_msgs/ThrottleInfoReport';106 }107 static md5sum() {108 //Returns md5sum for a message object109 return '6ed272050114755a930a6cf633944b48';110 }111 static messageDefinition() {112 // Returns full string definition for message113 return `114 Header header115 116 # Throttle Pedal117 float32 throttle_pc # Throttle pedal percent, range 0 to 1118 float32 throttle_rate # Throttle pedal change per second (1/s)119 QualityFactor throttle_pedal_qf # Non-zero is limp-home120 121 # Engine122 float32 engine_rpm # Engine Speed (rpm)123 124 # Gear Num125 GearNum gear_num # Gear Number126 127 ================================================================================128 MSG: std_msgs/Header129 # Standard metadata for higher-level stamped data types.130 # This is generally used to communicate timestamped data 131 # in a particular coordinate frame.132 # 133 # sequence ID: consecutively increasing ID 134 uint32 seq135 #Two-integer timestamp that is expressed as:136 # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')137 # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')138 # time-handling sugar is provided by the client library139 time stamp140 #Frame this data is associated with141 # 0: no frame142 # 1: global frame143 string frame_id144 145 ================================================================================146 MSG: dbw_mkz_msgs/QualityFactor147 uint8 value148 149 uint8 OK=0150 uint8 EMPTY=1151 uint8 CORRUPT=2152 uint8 FAULT=3153 154 ================================================================================155 MSG: dbw_mkz_msgs/GearNum156 uint8 num157 158 uint8 NONE=0159 uint8 DRIVE_D01=1160 uint8 DRIVE_D02=2161 uint8 DRIVE_D03=3162 uint8 DRIVE_D04=4163 uint8 DRIVE_D05=5164 uint8 DRIVE_D06=6165 uint8 DRIVE_D07=7166 uint8 DRIVE_D08=8167 uint8 DRIVE_D09=9168 uint8 DRIVE_D10=10169 uint8 NEUTRAL=16170 uint8 REVERSE_R01=17171 uint8 REVERSE_R02=18172 uint8 PARK=31173 `;174 }175 static Resolve(msg) {176 // deep-construct a valid message object instance of whatever was passed in177 if (typeof msg !== 'object' || msg === null) {178 msg = {};179 }180 const resolved = new ThrottleInfoReport(null);181 if (msg.header !== undefined) {182 resolved.header = std_msgs.msg.Header.Resolve(msg.header)183 }184 else {185 resolved.header = new std_msgs.msg.Header()186 }187 if (msg.throttle_pc !== undefined) {188 resolved.throttle_pc = msg.throttle_pc;189 }190 else {191 resolved.throttle_pc = 0.0192 }193 if (msg.throttle_rate !== undefined) {194 resolved.throttle_rate = msg.throttle_rate;195 }196 else {197 resolved.throttle_rate = 0.0198 }199 if (msg.throttle_pedal_qf !== undefined) {200 resolved.throttle_pedal_qf = QualityFactor.Resolve(msg.throttle_pedal_qf)201 }202 else {203 resolved.throttle_pedal_qf = new QualityFactor()204 }205 if (msg.engine_rpm !== undefined) {206 resolved.engine_rpm = msg.engine_rpm;207 }208 else {209 resolved.engine_rpm = 0.0210 }211 if (msg.gear_num !== undefined) {212 resolved.gear_num = GearNum.Resolve(msg.gear_num)213 }214 else {215 resolved.gear_num = new GearNum()216 }217 return resolved;218 }219};...

Full Screen

Full Screen

G5000_AutoThrottle.js

Source:G5000_AutoThrottle.js Github

copy

Full Screen

1class WT_G5000_AutoThrottle {2 /**3 * @param {WT_PlayerAirplane} airplane4 * @param {WT_AirplaneAltimeter} altimeter5 * @param {WT_InterpolatedLookupTable} clbN1Table6 * @param {WT_InterpolatedLookupTable} cruN1Table7 * @param {Number} [referenceEngineIndex]8 */9 constructor(airplane, altimeter, clbN1Table, cruN1Table, referenceEngineIndex = 1) {10 this._airplane = airplane;11 this._altimeter = altimeter;12 this._clbN1Table = clbN1Table;13 this._cruN1Table = cruN1Table;14 this._refEngine = airplane.engineering.getEngine(referenceEngineIndex);15 this._selectedAltitude = WT_Unit.FOOT.createNumber(0);16 this._indicatedAltitude = WT_Unit.FOOT.createNumber(0);17 this._cruLimitArmed = false;18 this._cruLimitArmedTime = 0;19 this._mode = WT_G5000_AutoThrottle.Mode.OFF;20 this._lastMode = WT_G5000_AutoThrottle.Mode.OFF;21 this._thrustLimitMode = WT_G5000_AutoThrottle.ThrustLimitMode.OFF;22 this._throttleLimit = airplane.autopilot.autoThrottleThrottleLimit();23 this._isAtMaxThrust = false;24 this._n1LookupKey = [0, 0];25 this._pressureAltitude = WT_Unit.FOOT.createNumber(0);26 this._isaDeltaTemp = WT_Unit.CELSIUS.createNumber(0);27 }28 /**29 * @readonly30 * @type {WT_G5000_AutoThrottle.Mode}31 */32 get mode() {33 return this._mode;34 }35 /**36 * @readonly37 * @type {WT_G5000_AutoThrottle.ThrustLimitMode}38 */39 get thrustLimitMode() {40 return this._thrustLimitMode;41 }42 /**43 * @readonly44 * @type {Boolean}45 */46 get isAtMaxThrust() {47 return this._isAtMaxThrust;48 }49 _updateMode() {50 this._lastMode = this.mode;51 let isActive = this._airplane.autopilot.isAutoThrottleActive();52 if (isActive) {53 if (this._airplane.autopilot.isFLCActive()) {54 let selectedAlt = this._airplane.autopilot.selectedAltitude(this._selectedAltitude);55 let indicatedAlt = this._altimeter.altitudeIndicated(this._indicatedAltitude);56 if (indicatedAlt.compare(selectedAlt) < 0) {57 this._mode = WT_G5000_AutoThrottle.Mode.CLIMB;58 } else {59 this._mode = WT_G5000_AutoThrottle.Mode.DESC;60 }61 } else {62 this._mode = WT_G5000_AutoThrottle.Mode.SPD;63 }64 } else {65 this._mode = WT_G5000_AutoThrottle.Mode.OFF;66 }67 }68 _updateThrustLimitMode() {69 if (this.mode === WT_G5000_AutoThrottle.Mode.CLIMB) {70 this._thrustLimitMode = WT_G5000_AutoThrottle.ThrustLimitMode.CLB;71 this._cruLimitArmed = false;72 } else {73 if (this._lastMode === WT_G5000_AutoThrottle.Mode.CLIMB) {74 this._cruLimitArmed = true;75 this._cruLimitArmedTime = SimVar.GetSimVarValue("E:ABSOLUTE TIME", "seconds");76 } else if (this.thrustLimitMode !== WT_G5000_AutoThrottle.ThrustLimitMode.CRU && this._cruLimitArmed) {77 let armedElapsedTime = SimVar.GetSimVarValue("E:ABSOLUTE TIME", "seconds") - this._cruLimitArmedTime;78 if (armedElapsedTime >= WT_G5000_AutoThrottle.CRU_ARM_DELAY) {79 this._thrustLimitMode = WT_G5000_AutoThrottle.ThrustLimitMode.CRU;80 this._cruLimitArmed = false;81 }82 }83 }84 }85 _updateN1LookupKey() {86 this._n1LookupKey[0] = this._airplane.environment.pressureAltitude(this._pressureAltitude).number;87 this._n1LookupKey[1] = this._airplane.environment.isaTemperatureDelta(this._isaDeltaTemp).number;88 }89 _calculateN1Limit(thrustLimitMode) {90 switch (thrustLimitMode) {91 case WT_G5000_AutoThrottle.ThrustLimitMode.CLB:92 this._updateN1LookupKey();93 return this._clbN1Table.get(this._n1LookupKey);94 case WT_G5000_AutoThrottle.ThrustLimitMode.CRU:95 this._updateN1LookupKey();96 return this._cruN1Table.get(this._n1LookupKey);97 case WT_G5000_AutoThrottle.ThrustLimitMode.GA:98 return 1;99 default:100 return 1;101 }102 }103 _setThrottleLimit(limit) {104 if (limit === this._throttleLimit) {105 return;106 }107 this._airplane.autopilot.setAutoThrottleThrottleLimit(limit);108 this._throttleLimit = limit;109 }110 _updateThrustLimit() {111 let isAtMaxThrust = false;112 let throttleLimit = this._throttleLimit;113 let n1Limit = this._calculateN1Limit(this.thrustLimitMode);114 if (n1Limit < 1) {115 let commandedN1 = this._refEngine.commandedN1();116 let diff = commandedN1 - n1Limit;117 let throttle = this._airplane.controls.throttlePosition(this._refEngine.index);118 if (diff > WT_G5000_AutoThrottle.N1_LIMIT_TOLERANCE) {119 let adjustment = Math.max(WT_G5000_AutoThrottle.THROTTLE_LIMIT_ADJUST_MIN, diff * WT_G5000_AutoThrottle.THROTTLE_LIMIT_ADJUST_FACTOR);120 throttleLimit -= adjustment;121 isAtMaxThrust = true;122 } else if (diff < -WT_G5000_AutoThrottle.N1_LIMIT_TOLERANCE) {123 if (throttle > this._throttleLimit - WT_G5000_AutoThrottle.THROTTLE_LIMIT_TOLERANCE) {124 let adjustment = Math.max(WT_G5000_AutoThrottle.THROTTLE_LIMIT_ADJUST_MIN, -diff * WT_G5000_AutoThrottle.THROTTLE_LIMIT_ADJUST_FACTOR);125 throttleLimit += adjustment;126 }127 } else {128 isAtMaxThrust = throttle > this._throttleLimit - WT_G5000_AutoThrottle.THROTTLE_LIMIT_TOLERANCE;129 }130 } else {131 throttleLimit = 1;132 }133 this._setThrottleLimit(throttleLimit);134 this._isAtMaxThrust = isAtMaxThrust;135 }136 update() {137 this._updateMode();138 this._updateThrustLimitMode();139 this._updateThrustLimit();140 }141}142WT_G5000_AutoThrottle.CRU_ARM_DELAY = 600; // seconds143WT_G5000_AutoThrottle.N1_LIMIT_TOLERANCE = 0.005;144WT_G5000_AutoThrottle.THROTTLE_LIMIT_TOLERANCE = 0.01;145WT_G5000_AutoThrottle.THROTTLE_LIMIT_ADJUST_FACTOR = 0.5;146WT_G5000_AutoThrottle.THROTTLE_LIMIT_ADJUST_MIN = 0.001;147/**148 * @enum {Number}149 */150WT_G5000_AutoThrottle.Mode = {151 OFF: 0,152 SPD: 1,153 CLIMB: 2,154 DESC: 3155};156/**157 * @enum {Number}158 */159WT_G5000_AutoThrottle.ThrustLimitMode = {160 OFF: 1,161 CLB: 2,162 CRU: 3,163 GA: 4...

Full Screen

Full Screen

yui-throttle-coverage.js

Source:yui-throttle-coverage.js Github

copy

Full Screen

...31 calledFunctions: 0,32 path: "build/yui-throttle/yui-throttle.js",33 code: []34};35_yuitest_coverage["build/yui-throttle/yui-throttle.js"].code=["YUI.add('yui-throttle', function (Y, NAME) {","","/**","Throttles a call to a method based on the time between calls. This method is attached","to the `Y` object and is <a href=\"../classes/YUI.html#method_throttle\">documented there</a>.",""," var fn = Y.throttle(function() {"," counter++;"," });",""," for (i; i< 35000; i++) {"," out++;"," fn();"," }","","","@module yui","@submodule yui-throttle","*/","","/*! Based on work by Simon Willison: http://gist.github.com/292562 */","/**"," * Throttles a call to a method based on the time between calls."," * @method throttle"," * @for YUI"," * @param fn {function} The function call to throttle."," * @param ms {int} The number of milliseconds to throttle the method call."," * Can set globally with Y.config.throttleTime or by call. Passing a -1 will"," * disable the throttle. Defaults to 150."," * @return {function} Returns a wrapped function that calls fn throttled."," * @since 3.1.0"," */","Y.throttle = function(fn, ms) {"," ms = (ms) ? ms : (Y.config.throttleTime || 150);",""," if (ms === -1) {"," return function() {"," fn.apply(null, arguments);"," };"," }",""," var last = Y.Lang.now();",""," return function() {"," var now = Y.Lang.now();"," if (now - last > ms) {"," last = now;"," fn.apply(null, arguments);"," }"," };","};","","","}, '3.7.3', {\"requires\": [\"yui-base\"]});"];36_yuitest_coverage["build/yui-throttle/yui-throttle.js"].lines = {"1":0,"33":0,"34":0,"36":0,"37":0,"38":0,"42":0,"44":0,"45":0,"46":0,"47":0,"48":0};37_yuitest_coverage["build/yui-throttle/yui-throttle.js"].functions = {"(anonymous 2):37":0,"(anonymous 3):44":0,"throttle:33":0,"(anonymous 1):1":0};38_yuitest_coverage["build/yui-throttle/yui-throttle.js"].coveredLines = 12;39_yuitest_coverage["build/yui-throttle/yui-throttle.js"].coveredFunctions = 4;40_yuitest_coverline("build/yui-throttle/yui-throttle.js", 1);41YUI.add('yui-throttle', function (Y, NAME) {42/**43Throttles a call to a method based on the time between calls. This method is attached44to the `Y` object and is <a href="../classes/YUI.html#method_throttle">documented there</a>.45 var fn = Y.throttle(function() {46 counter++;47 });48 for (i; i< 35000; i++) {49 out++;50 fn();51 }52@module yui53@submodule yui-throttle54*/55/*! Based on work by Simon Willison: http://gist.github.com/292562 */56/**57 * Throttles a call to a method based on the time between calls.58 * @method throttle59 * @for YUI...

Full Screen

Full Screen

throttler.js

Source:throttler.js Github

copy

Full Screen

...19 * @param {string || number} identifier20 * @param {string} throttleType21 * @returns {boolean}22 */23 throttle(identifier, throttleType) {24 if (this._hasBeenThrottled(identifier, throttleType)) {25 return true;26 }27 this._addThrottle(identifier, throttleType);28 return this._shouldThrottle(identifier, throttleType);29 };30 /**31 * Sets the throttle cutoff limits on initialization.32 *33 * @private34 */35 _setLimits() {36 this._limits[throttleTypes.signInCode] = 5;37 this._limits[throttleTypes.signInConformation] = 5;...

Full Screen

Full Screen

throttle.js

Source:throttle.js Github

copy

Full Screen

1// Copyright 2007 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview Definition of the goog.async.Throttle class.16 *17 * @see ../demos/timers.html18 */19goog.provide('goog.Throttle');20goog.provide('goog.async.Throttle');21goog.require('goog.Disposable');22goog.require('goog.Timer');23/**24 * Throttle will perform an action that is passed in no more than once25 * per interval (specified in milliseconds). If it gets multiple signals26 * to perform the action while it is waiting, it will only perform the action27 * once at the end of the interval.28 * @param {Function} listener Function to callback when the action is triggered.29 * @param {number} interval Interval over which to throttle. The handler can30 * only be called once per interval.31 * @param {Object=} opt_handler Object in whose scope to call the listener.32 * @constructor33 * @extends {goog.Disposable}34 */35goog.async.Throttle = function(listener, interval, opt_handler) {36 goog.Disposable.call(this);37 /**38 * Function to callback39 * @type {Function}40 * @private41 */42 this.listener_ = listener;43 /**44 * Interval for the throttle time45 * @type {number}46 * @private47 */48 this.interval_ = interval;49 /**50 * "this" context for the listener51 * @type {Object|undefined}52 * @private53 */54 this.handler_ = opt_handler;55 /**56 * Cached callback function invoked after the throttle timeout completes57 * @type {Function}58 * @private59 */60 this.callback_ = goog.bind(this.onTimer_, this);61};62goog.inherits(goog.async.Throttle, goog.Disposable);63/**64 * A deprecated alias.65 * @deprecated Use goog.async.Throttle instead.66 * @constructor67 */68goog.Throttle = goog.async.Throttle;69/**70 * Indicates that the action is pending and needs to be fired.71 * @type {boolean}72 * @private73 */74goog.async.Throttle.prototype.shouldFire_ = false;75/**76 * Indicates the count of nested pauses currently in effect on the throttle.77 * When this count is not zero, fired actions will be postponed until the78 * throttle is resumed enough times to drop the pause count to zero.79 * @type {number}80 * @private81 */82goog.async.Throttle.prototype.pauseCount_ = 0;83/**84 * Timer for scheduling the next callback85 * @type {?number}86 * @private87 */88goog.async.Throttle.prototype.timer_ = null;89/**90 * Notifies the throttle that the action has happened. It will throttle the call91 * so that the callback is not called too often according to the interval92 * parameter passed to the constructor.93 */94goog.async.Throttle.prototype.fire = function() {95 if (!this.timer_ && !this.pauseCount_) {96 this.doAction_();97 } else {98 this.shouldFire_ = true;99 }100};101/**102 * Cancels any pending action callback. The throttle can be restarted by103 * calling {@link #fire}.104 */105goog.async.Throttle.prototype.stop = function() {106 if (this.timer_) {107 goog.Timer.clear(this.timer_);108 this.timer_ = null;109 this.shouldFire_ = false;110 }111};112/**113 * Pauses the throttle. All pending and future action callbacks will be114 * delayed until the throttle is resumed. Pauses can be nested.115 */116goog.async.Throttle.prototype.pause = function() {117 this.pauseCount_++;118};119/**120 * Resumes the throttle. If doing so drops the pausing count to zero, pending121 * action callbacks will be executed as soon as possible, but still no sooner122 * than an interval's delay after the previous call. Future action callbacks123 * will be executed as normal.124 */125goog.async.Throttle.prototype.resume = function() {126 this.pauseCount_--;127 if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {128 this.shouldFire_ = false;129 this.doAction_();130 }131};132/** @inheritDoc */133goog.async.Throttle.prototype.disposeInternal = function() {134 goog.async.Throttle.superClass_.disposeInternal.call(this);135 this.stop();136};137/**138 * Handler for the timer to fire the throttle139 * @private140 */141goog.async.Throttle.prototype.onTimer_ = function() {142 this.timer_ = null;143 if (this.shouldFire_ && !this.pauseCount_) {144 this.shouldFire_ = false;145 this.doAction_();146 }147};148/**149 * Calls the callback150 * @private151 */152goog.async.Throttle.prototype.doAction_ = function() {153 this.timer_ = goog.Timer.callOnce(this.callback_, this.interval_);154 this.listener_.call(this.handler_);...

Full Screen

Full Screen

throttle_test.js

Source:throttle_test.js Github

copy

Full Screen

1// Copyright 2006 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.async.ThrottleTest');15goog.setTestOnly('goog.async.ThrottleTest');16goog.require('goog.async.Throttle');17goog.require('goog.testing.MockClock');18goog.require('goog.testing.jsunit');19function testThrottle() {20 var clock = new goog.testing.MockClock(true);21 var callBackCount = 0;22 var callBackFunction = function() {23 callBackCount++;24 };25 var throttle = new goog.async.Throttle(callBackFunction, 100);26 assertEquals(0, callBackCount);27 throttle.fire();28 assertEquals(1, callBackCount);29 throttle.fire();30 assertEquals(1, callBackCount);31 throttle.fire();32 throttle.fire();33 assertEquals(1, callBackCount);34 clock.tick(101);35 assertEquals(2, callBackCount);36 clock.tick(101);37 assertEquals(2, callBackCount);38 throttle.fire();39 assertEquals(3, callBackCount);40 throttle.fire();41 assertEquals(3, callBackCount);42 throttle.stop();43 clock.tick(101);44 assertEquals(3, callBackCount);45 throttle.fire();46 assertEquals(4, callBackCount);47 clock.tick(101);48 assertEquals(4, callBackCount);49 throttle.fire();50 throttle.fire();51 assertEquals(5, callBackCount);52 throttle.pause();53 throttle.resume();54 assertEquals(5, callBackCount);55 throttle.pause();56 clock.tick(101);57 assertEquals(5, callBackCount);58 throttle.resume();59 assertEquals(6, callBackCount);60 clock.tick(101);61 assertEquals(6, callBackCount);62 throttle.pause();63 throttle.fire();64 assertEquals(6, callBackCount);65 clock.tick(101);66 assertEquals(6, callBackCount);67 throttle.resume();68 assertEquals(7, callBackCount);69 throttle.pause();70 throttle.pause();71 clock.tick(101);72 throttle.fire();73 throttle.resume();74 assertEquals(7, callBackCount);75 throttle.resume();76 assertEquals(8, callBackCount);77 throttle.pause();78 throttle.pause();79 throttle.fire();80 throttle.resume();81 clock.tick(101);82 assertEquals(8, callBackCount);83 throttle.resume();84 assertEquals(9, callBackCount);85 clock.uninstall();86}87function testThrottleScopeBinding() {88 var interval = 500;89 var mockClock = new goog.testing.MockClock(true);90 var x = {'y': 0};91 new goog.async.Throttle(function() {92 ++this['y'];93 }, interval, x).fire();94 assertEquals(1, x['y']);95 mockClock.uninstall();96}97function testThrottleArgumentBinding() {98 var interval = 500;99 var mockClock = new goog.testing.MockClock(true);100 var calls = 0;101 var throttle = new goog.async.Throttle(function(a, b, c) {102 ++calls;103 assertEquals(3, a);104 assertEquals('string', b);105 assertEquals(false, c);106 }, interval);107 throttle.fire(3, 'string', false);108 assertEquals(1, calls);109 // fire should always pass the last arguments passed to it into the decorated110 // function, even if called multiple times.111 throttle.fire();112 mockClock.tick(interval / 2);113 throttle.fire(8, null, true);114 throttle.fire(3, 'string', false);115 mockClock.tick(interval);116 assertEquals(2, calls);117 mockClock.uninstall();118}119function testThrottleArgumentAndScopeBinding() {120 var interval = 500;121 var mockClock = new goog.testing.MockClock(true);122 var x = {'calls': 0};123 var throttle = new goog.async.Throttle(function(a, b, c) {124 ++this['calls'];125 assertEquals(3, a);126 assertEquals('string', b);127 assertEquals(false, c);128 }, interval, x);129 throttle.fire(3, 'string', false);130 assertEquals(1, x['calls']);131 // fire should always pass the last arguments passed to it into the decorated132 // function, even if called multiple times.133 throttle.fire();134 mockClock.tick(interval / 2);135 throttle.fire(8, null, true);136 throttle.fire(3, 'string', false);137 mockClock.tick(interval);138 assertEquals(2, x['calls']);139 mockClock.uninstall();...

Full Screen

Full Screen

throttle-binding-behavior.js

Source:throttle-binding-behavior.js Github

copy

Full Screen

2define(['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {3 'use strict';4 exports.__esModule = true;5 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }6 function throttle(newValue) {7 var _this = this;8 var state = this.throttleState;9 var elapsed = +new Date() - state.last;10 if (elapsed >= state.delay) {11 clearTimeout(state.timeoutId);12 state.timeoutId = null;13 state.last = +new Date();14 this.throttledMethod(newValue);15 return;16 }17 state.newValue = newValue;18 if (state.timeoutId === null) {19 state.timeoutId = setTimeout(function () {20 state.timeoutId = null;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12var webdriverio = require('webdriverio');13var options = {14 desiredCapabilities: {15 }16};17 .remote(options)18 .init()19 .getTitle().then(function(title) {20 console.log('Title was: ' + title);21 })22 .end();23var webdriverio = require('webdriverio');24var options = {25 desiredCapabilities: {26 }27};28 .remote(options)29 .init()30 .getTitle().then(function(title) {31 console.log('Title was: ' + title);32 })33 .end();34var webdriverio = require('webdriverio');35var options = {36 desiredCapabilities: {37 }38};39 .remote(options)40 .init()41 .getTitle().then(function(title) {42 console.log('Title was: ' + title);43 })44 .end();45var webdriverio = require('webdriverio');46var options = {47 desiredCapabilities: {48 }49};50 .remote(options)51 .init()52 .getTitle().then(function(title) {53 console.log('Title was: ' + title);54 })55 .end();56var webdriverio = require('webdriverio');57var options = {58 desiredCapabilities: {59 }60};61 .remote(options)62 .init()63 .getTitle().then(function(title

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12 console.log('Title was: ' + title);13}).end();14var webdriverio = require('webdriverio');15var options = {16 desiredCapabilities: {17 }18};19 .remote(options)20 .init()21 .getTitle().then(function(title) {22 console.log('Title was: ' + title);23 })24 .end();25 console.log('Title was: ' + title);26}).end();27 console.log('Title was: ' + title);28}).end();29 console.log('Title was: ' + title);30}).end();31 console.log('Title was: ' + title);32}).end();33 console.log('Title was: ' + title);34}).end();35 console.log('Title was: ' + title);36}).end();37 console.log('Title was: ' + title);38}).end();39 console.log('Title was: ' + title);40}).end();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .setValue('#lst-ib', 'webdriverio')9 .throttle(1000, 1000, 1000)10 .click('input[name="btnK"]')11 .getTitle().then(function(title) {12 console.log('Title was: ' + title);13 })14 .end();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7 .init()8 .setValue('#lst-ib', 'webdriverio')9 .keys('\uE007')10 .getTitle().then(function(title) {11 console.log('Title was: ' + title);12 })13 .end();14var webdriverio = require('webdriverio');15var options = {16 desiredCapabilities: {17 }18};19var client = webdriverio.remote(options);20 .init()21 .setValue('#lst-ib', 'webdriverio')22 .keys('\uE007')23 .getTitle().then(function(title) {24 console.log('Title was: ' + title);25 })26 .end();27var webdriverio = require('webdriverio');28var options = {29 desiredCapabilities: {30 }31};32var client = webdriverio.remote(options);33 .init()34 .setValue('#lst-ib', 'webdriverio')35 .keys('\uE007')36 .getTitle().then(function(title) {37 console.log('Title was: ' + title);38 })39 .end();40var webdriverio = require('webdriverio');41var options = {42 desiredCapabilities: {43 }44};45var client = webdriverio.remote(options);46 .init()47 .setValue('#lst-ib', 'webdriverio')48 .keys('\uE007')49 .getTitle().then(function(title) {50 console.log('Title was: ' + title);

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Throttle', () => {2 it('should throttle the browser', () => {3 browser.throttle(100, 1000, 1000)4 browser.pause(5000)5 browser.throttle(0, 0, 0)6 browser.pause(5000)7 })8})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("Throttle", () => {2 it("should throttle the network", async () => {3 await browser.throttleNetwork("Regular 3G");4 await browser.pause(5000);5 await browser.throttleNetwork("Regular 3G", 100, 1000);6 await browser.pause(5000);7 await browser.throttleNetwork("Regular 3G", 100, 1000, 100);8 await browser.pause(5000);9 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100);10 await browser.pause(5000);11 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100);12 await browser.pause(5000);13 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100);14 await browser.pause(5000);15 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100, 100);16 await browser.pause(5000);17 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100, 100, 100);18 await browser.pause(5000);19 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100, 100, 100, 100);20 await browser.pause(5000);21 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100, 100, 100, 100, 100);22 await browser.pause(5000);23 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100, 100, 100, 100, 100, 100);24 await browser.pause(5000);25 await browser.throttleNetwork("Regular 3G", 100, 1000, 100, 100, 100, 100, 100, 100, 100, 100

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function () {2 it('should do something', function () {3 browser.throttle('1000', '1000', '1000', '1000');4 browser.pause(10000);5 browser.throttle('0', '0', '0', '0');6 });7});8Your name to display (optional):9Your name to display (optional):

Full Screen

WebdriverIO Tutorial

Wondering what could be a next-gen browser and mobile test automation framework that is also simple and concise? Yes, that’s right, it's WebdriverIO. Since the setup is very easy to follow compared to Selenium testing configuration, you can configure the features manually thereby being the center of attraction for automation testing. Therefore the testers adopt WedriverIO to fulfill their needs of browser testing.

Learn to run automation testing with WebdriverIO tutorial. Go from a beginner to a professional automation test expert with LambdaTest WebdriverIO tutorial.

Chapters

  1. Running Your First Automation Script - Learn the steps involved to execute your first Test Automation Script using WebdriverIO since the setup is very easy to follow and the features can be configured manually.

  2. Selenium Automation With WebdriverIO - Read more about automation testing with WebdriverIO and how it supports both browsers and mobile devices.

  3. Browser Commands For Selenium Testing - Understand more about the barriers faced while working on your Selenium Automation Scripts in WebdriverIO, the ‘browser’ object and how to use them?

  4. Handling Alerts & Overlay In Selenium - Learn different types of alerts faced during automation, how to handle these alerts and pops and also overlay modal in WebdriverIO.

  5. How To Use Selenium Locators? - Understand how Webdriver uses selenium locators in a most unique way since having to choose web elements very carefully for script execution is very important to get stable test results.

  6. Deep Selectors In Selenium WebdriverIO - The most popular automation testing framework that is extensively adopted by all the testers at a global level is WebdriverIO. Learn how you can use Deep Selectors in Selenium WebdriverIO.

  7. Handling Dropdown In Selenium - Learn more about handling dropdowns and how it's important while performing automated browser testing.

  8. Automated Monkey Testing with Selenium & WebdriverIO - Understand how you can leverage the amazing quality of WebdriverIO along with selenium framework to automate monkey testing of your website or web applications.

  9. JavaScript Testing with Selenium and WebdriverIO - Speed up your Javascript testing with Selenium and WebdriverIO.

  10. Cross Browser Testing With WebdriverIO - Learn more with this step-by-step tutorial about WebdriverIO framework and how cross-browser testing is done with WebdriverIO.

Run Webdriverio automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful