note throttled functions require cancellation to avoid delaying node shutdown see test/throttle-5s.js
177950
function throttleMs(f, waitMs) {
  return _.throttle(f, ms(waitMs), {leading:true, trailing:false});
}
757284
function _schedule() {
    // do not _schedule when there are timeouts in progress
    // this can be the case with async timeouts in non-paced mode.
    // _schedule will be executed again when all async timeouts are finished.
    if (!paced && Object.keys(current).length > 0) {
      return;
    }

    var next = timeouts[0];

    // cancel timer when running
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }

    if (running && next) {
      // schedule next timeout
      var time = next.time;
      var delay = time - timer.now();
      var realDelay = paced ? delay / rate : 0;

      function onTimeout() {
        // when running in non-paced mode, update the hyperTime to
        // adjust the time of the current event
        if (!paced) {
          hyperTime = (time > hyperTime && isFinite(time)) ? time : hyperTime;
        }

        // grab all expired timeouts from the queue
        var expired = _getExpiredTimeouts(time);
        // note: expired.length can never be zero (on every change of the queue, we reschedule)

        // execute all expired timeouts
        if (paced) {
          // in paced mode, we fire all timeouts in parallel,
          // and don't await their completion (they can do async operations)
          expired.forEach(function (timeout) {
            _execTimeout(timeout);
          });

          // schedule the next round
          _schedule();
        }
        else {
          // in non-paced mode, we execute all expired timeouts serially,
          // and wait for their completion in order to guarantee deterministic
          // order of execution
          function next() {
            var timeout = expired.shift();
            if (timeout) {
              _execTimeout(timeout, next);
            }
            else {
              // schedule the next round
              _schedule();
            }
          }
          next();
        }
      }

      timeoutId = setTimeout(onTimeout, Math.round(realDelay));
      // Note: Math.round(realDelay) is to defeat a bug in node.js v0.10.30,
      //       see https://github.com/joyent/node/issues/8065
    }
  }
435148
function (canceller) {
        var self = this;
        this._canceller = canceller;
        this._timeout = null;
        this._timer = null;

        this.handled = false;

        this.waiting = [];
        this.result = undefined;
        this.isError = false;
        this.finished = false;

        //this.currentContextHandler = contextHandler.getHandler && contextHandler.getHandler();
        this.__defineGetter__('promise', this.getPromise);
    }
136730
function()
			{
				var func = todo.shift();
				if (!func)
				{
					// all done!
					if (callback) callback(false);
					return;
				}

				if (token_fetch.indexOf(func.func) >= 0)
				{
					// if we're actually calling a token fetch function, skip!
					process.nextTick(step);
				}
				else
				{
					func.func(function(error) {
						if (error)
						{
							// token fetching error!
							if (callback) callback(func.name + " :: " + error);
							return;
						}

						// do next step
						process.nextTick(step);
					});
				}
			}
457834
def connect_cancel(self, functions):
        '''
        '''
        self._cancel_functions = []
        for func in functions:
            if isinstance(func, basestring) and hasattr(self, func) and callable(getattr(self, func)):
                self._cancel_functions.append(getattr(self, func))
            elif callable(func):
                self._cancel_functions.append(func)
            else:
                raise ValueError("Unknown function %s" % str(func))
624921
function () {

                var that = this,
                    paramHandler = this.params.handler,
                    params = util.mixin({}, this.params);

                //wrap the handler callbacks in a cancel check
                function handler(responseCode, data, ioArgs) {
                    that.xhr = ioArgs.xhr;
                    that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0;
                    if (that.canceled) {
                        logger.debug("Request [" + that.id + "] was canceled, not calling handler");
                    } else {
                        that.pending = false;
                        that.complete = true;
                        paramHandler(responseCode, data, ioArgs);
                    }
                }

                if (this.canceled) {
                    logger.debug("Request [" + that.id + "] was canceled, not executing");
                } else {
                    this.pending = true;
                    this.fn(util.mixin(params, {
                        handler: handler
                    }));
                }
            }
770957
function(fnc, cacheId, delay, scope, parameters, strategy) {
            var self = this,
                LOOP = "loop";

            if (!fnc) {
                return;
            }

            cacheId = cacheId || fnc.toString();
            scope = scope || this;
            parameters = parameters || [];
            strategy = strategy || LOOP;

            if (delay === 0) {
                // immediately invoke function
                fnc.apply(scope, parameters);
                return;
            }

            delay = delay || 300;
            if (this.$debounceTimeoutMap[cacheId]) {
                // timer registered

                if (strategy === LOOP) {
                    return;
                }

                clearTimeout(this.$debounceTimeoutMap[cacheId]);
            }

            this.$debounceTimeoutMap[cacheId] = setTimeout(function() {
                delete self.$debounceTimeoutMap[cacheId];
                fnc.apply(scope, parameters);
            }, delay);
        }
1245205
async def message_throttled(self, message: types.Message, throttled: Throttled):
        
        handler = current_handler.get()
        dispatcher = Dispatcher.get_current()
        if handler:
            key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
        else:
            key = f"{self.prefix}_message"

        # Calculate how many time is left till the block ends
        delta = throttled.rate - throttled.delta

        # Prevent flooding
        if throttled.exceeded_count <= 2:
            await message.reply('Too many requests! ')

        # Sleep.
        await asyncio.sleep(delta)

        # Check lock status
        thr = await dispatcher.check_key(key)

        # If current message is not last with current key - do not send message
        if thr.exceeded_count == throttled.exceeded_count:
            await message.reply('Unlocked.')
312288
async function waitForEvent(env, event, breakerFunction, timeout = 5000, interval = 10) {
    const { type, urlPattern } = event;
    let intervalId, timeoutId;
    await new Promise((resolve, reject) => {
        const callback = {
            fn: ({ error }) => {
                clearTimeout(timeoutId);
                clearInterval(intervalId);
                if (error) {
                    reject(error);
                } else {
                    resolve();
                }
            },
            urlPattern,
        };

        timeoutId = setTimeout(() => {
            env.removeCallback(type, callback);
            clearInterval(intervalId);
            reject(new Error('Page navigation timeout'));
        }, timeout);

        intervalId = setInterval(() => {
            if (breakerFunction()) {
                clearTimeout(timeoutId);
                clearInterval(intervalId);
                env.removeCallback(type, callback);
                reject(new Error('Function was terminated by breaker'))
            }
        }, interval);

        env.addCallback(type, callback);
    });

    if (type === 'navigation') {
        await env._injectFiles(env._getVendors());
    }
}
505106
function onDisconnect() {
	var rids = Object.keys( cache ),
		len = rids.length,
		i;

	// TODO: log
	console.log( process.pid, 'disconnected' );

	// Abort any pending requests...
	for ( i = 0; i < len; i++ ) {
		cache[ rids[i] ].abort();

		// TODO: log
		console.log( process.pid, 'aborting request: ', rids[ i ] );
	}
}
1183581
function functionsWithinRange(startMillis, endMillis) {
    var fnsToRun = [];
    for (var timeoutKey in scheduledFunctions) {
      var scheduledFunc = scheduledFunctions[timeoutKey];
      if (scheduledFunc &&
          scheduledFunc.runAtMillis >= startMillis &&
            scheduledFunc.runAtMillis <= endMillis) {
        //remove fn -- we'll reschedule later if it is recurring.
        self.removeFunctionWithId(timeoutKey);
        if (!scheduledFunc.recurring) {
          fnsToRun.push(scheduledFunc); // schedules each function only once
        } else {
          fnsToRun.push(buildNthInstanceOf(scheduledFunc, 0));
          var additionalTimesFnRunsInRange =
            Math.floor((endMillis - scheduledFunc.runAtMillis) / scheduledFunc.millis);
          for (var i = 0; i < additionalTimesFnRunsInRange; i++) {
            fnsToRun.push(buildNthInstanceOf(scheduledFunc, i + 1));
          }
          reschedule(buildNthInstanceOf(scheduledFunc, additionalTimesFnRunsInRange));
        }
      }
    }

    return fnsToRun;
  }
450858
function(func) {
		var timeout, timestamp;
		var wait = 99;
		var run = function(){
			timeout = null;
			func();
		};
		var later = function() {
			var last = Date.now() - timestamp;

			if (last < wait) {
				setTimeout(later, wait - last);
			} else {
				(requestIdleCallback || run)(run);
			}
		};

		return function() {
			timestamp = Date.now();

			if (!timeout) {
				timeout = setTimeout(later, wait);
			}
		};
	}
631402
function throttle(func, delay) {
      var recent;
      return function throttled() {
        var context = this;
        var args = arguments;
        var now = $mdUtil.now();

        if (!recent || (now - recent > delay)) {
          func.apply(context, args);
          recent = now;
        }
      };
    }
340827
function preventAll () {
    function shield (req) {
      req.prevent();
    }
    measly.on('create', shield);
    text(preventButton, 'Shield On..');
    preventButton.classList.add('cm-prevent-on');

    setTimeout(function () {
      measly.off('create', shield);
      text(preventButton, 'Prevent for 5s');
      preventButton.classList.remove('cm-prevent-on');
    }, 5000);
  }
144930
async def _throttled_request(self, request):
        ''''''
        disconnect = False
        try:
            timeout = self.processing_timeout
            async with timeout_after(timeout):
                async with self._incoming_concurrency:
                    if self.is_closing():
                        return
                    if self._cost_fraction:
                        await sleep(self._cost_fraction * self.cost_sleep)
                    result = await self.handle_request(request)
        except (ProtocolError, RPCError) as e:
            result = e
        except TaskTimeout:
            self.logger.info(f'incoming request {request} timed out after {timeout} secs')
            result = RPCError(JSONRPC.SERVER_BUSY, 'server busy - request timed out')
        except ReplyAndDisconnect as e:
            result = e.result
            disconnect = True
        except ExcessiveSessionCostError:
            result = RPCError(JSONRPC.EXCESSIVE_RESOURCE_USAGE, 'excessive resource usage')
            disconnect = True
        except CancelledError:
            raise
        except Exception:
            self.logger.exception(f'exception handling {request}')
            result = RPCError(JSONRPC.INTERNAL_ERROR, 'internal server error')

        if isinstance(request, Request):
            message = request.send_result(result)
            if message:
                await self._send_message(message)
        if isinstance(result, Exception):
            self._bump_errors(result)
        if disconnect:
            await self.close()
1324107
function setDeferredTimeout(deferred, delay) {
        var timer = setTimeout(function () {
            deferred.reject("timeout");
        }, delay);
        deferred.always(function () { clearTimeout(timer); });
    }
678979
function shutdownHandler(job) {
   // Change status to IN_PROGRESS
   job.inProgress({ operation: job.operation, step: 'attempting' }, function(err) { 
      showJobsError(err);

      var delay = (isUndefined(job.document.delay) ? '0' : job.document.delay.toString());

      // Check for adequate permissions to perform shutdown, use -k option to do dry run
      //
      // User account running node.js agent must have passwordless sudo access on /sbin/shutdown
      // Recommended online search for permissions setup instructions https://www.google.com/search?q=passwordless+sudo+access+instructions
      exec('sudo /sbin/shutdown -k +' + delay, function (err) { 
         if (!isUndefined(err)) {
            job.failed({ operation: job.operation, errorCode: 'ERR_SYSTEM_CALL_FAILED', errorMessage: 'unable to execute shutdown, check passwordless sudo permissions on agent', 
                         error: errorToString(err) }, showJobsError);
         } else {
            job.succeeded({ operation: job.operation, step: 'initiated' }, function (err) {
               showJobsError(err);
               exec('sudo /sbin/shutdown +' + delay);
            });
         }
      });
   });
}