本文整理汇总了TypeScript中underscore.throttle函数的典型用法代码示例。如果您正苦于以下问题:TypeScript throttle函数的具体用法?TypeScript throttle怎么用?TypeScript throttle使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了throttle函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: constructor
constructor(name: string, redux: AppRedux) {
// important: run init in any case in order to run @load_url_target,
// but do not actually create a session if @name is '' or null/undefined
this.load_url_target = this.load_url_target.bind(this);
this.init_local_storage = this.init_local_storage.bind(this);
this.save = this.save.bind(this);
this.close_project = this.close_project.bind(this);
this._save_to_local_storage = this._save_to_local_storage.bind(this);
this._save_to_local_storage_closed = this._save_to_local_storage_closed.bind(
this
);
this.restore = this.restore.bind(this);
this._restore_project = this._restore_project.bind(this);
this._restore_all = this._restore_all.bind(this);
this._load_from_local_storage = this._load_from_local_storage.bind(this);
// init attributes
this.name = name;
this.redux = redux;
// actual initialization
if (webapp_client.is_signed_in()) {
this.init_local_storage();
} else {
webapp_client.once("signed_in", () => {
return this.init_local_storage();
});
}
if (this.name) {
this.save = throttle(this.save, 1000);
}
}
示例2: link
link: function link(scope) {
function clickHandler() {
dimActivityTrackerService.track();
}
function visibilityHandler() {
if ($document[0].hidden === false) {
dimActivityTrackerService.track();
refreshAccountData();
}
}
$document.on('click', clickHandler);
$document.on('visibilitychange', visibilityHandler);
$document.on('online', refreshAccountData);
const ONE_MINUTE = 60 * 1000;
const FIVE_MINUTES = 5 * 60 * 1000;
const ONE_HOUR = 60 * 60 * 1000;
const refresh = _.throttle(() => {
// Individual pages should listen to this event and decide what to refresh,
// and their services should decide how to cache/dedup refreshes.
// This event should *NOT* be listened to by services!
// TODO: replace this with an observable?
$rootScope.$broadcast('dim-refresh');
}, ONE_MINUTE, { trailing: false });
const activeWithinLastHour = dimActivityTrackerService.activeWithinTimespan
.bind(dimActivityTrackerService, ONE_HOUR);
function refreshAccountData() {
const dimHasNoActivePromises = !loadingTracker.active();
const userWasActiveInTheLastHour = activeWithinLastHour();
const isDimVisible = !$document.hidden;
const isOnline = navigator.onLine;
if (dimHasNoActivePromises && userWasActiveInTheLastHour && isDimVisible && isOnline) {
refresh();
}
}
let refreshAccountDataInterval = $timeout(refreshAccountData, FIVE_MINUTES);
scope.$on('$destroy', () => {
$document.off('click', clickHandler);
$document.off('visibilitychange', visibilityHandler);
$document.off('online', refreshAccountData);
$timeout.cancel(refreshAccountDataInterval);
});
// Every time we refresh for any reason, reset the timer
scope.$on('dim-refresh', () => {
$timeout.cancel(refreshAccountDataInterval);
refreshAccountDataInterval = $timeout(refreshAccountData, FIVE_MINUTES);
});
}
示例3: init_term
async function init_term() {
const args: string[] = [];
if (options.args != null) {
for (let arg of options.args) {
if (typeof arg === "string") {
args.push(arg);
}
}
} else {
const init_filename: string = console_init_filename(path);
if (await exists(init_filename)) {
args.push("--init-file");
args.push(path_split(init_filename).tail);
}
}
const s = path_split(path);
const env = merge({ COCALC_TERMINAL_FILENAME: s.tail }, process.env);
if (options.env != null) {
merge(env, options.env);
}
const command = options.command ? options.command : "/bin/bash";
const cwd = s.head;
try {
terminals[name].history = (await callback(readFile, path)).toString();
} catch (err) {
console.log(`failed to load ${path} from disk`);
}
const term = spawn(command, args, { cwd, env });
logger.debug("terminal", "init_term", name, "pid=", term.pid, "args", args);
terminals[name].term = term;
const save_history_to_disk = throttle(async () => {
try {
await callback(writeFile, path, terminals[name].history);
} catch (err) {
console.log(`failed to save ${path} to disk`);
}
}, 15000);
term.on("data", function(data): void {
//logger.debug("terminal: term --> browsers", name, data);
handle_backend_messages(data);
terminals[name].history += data;
save_history_to_disk();
const n = terminals[name].history.length;
if (n >= MAX_HISTORY_LENGTH) {
logger.debug("terminal data -- truncating");
terminals[name].history = terminals[name].history.slice(
n - MAX_HISTORY_LENGTH / 2
);
const last = terminals[name].last_truncate_time;
const now = new Date().valueOf();
terminals[name].last_truncate_time = now;
logger.debug("terminal", now, last, now - last, truncate_thresh_ms);
if (now - last <= truncate_thresh_ms) {
// getting a huge amount of data quickly.
if (!terminals[name].truncating) {
channel.write({ cmd: "burst" });
}
terminals[name].truncating += data.length;
setTimeout(check_if_still_truncating, check_interval_ms);
if (terminals[name].truncating >= 5 * MAX_HISTORY_LENGTH) {
// only start sending control+c if output has been completely stuck
// being truncated several times in a row -- it has to be a serious non-stop burst...
term.write("\u0003");
}
return;
} else {
terminals[name].truncating = 0;
}
}
if (!terminals[name].truncating) {
channel.write(data);
}
});
let backend_messages_state: "NONE" | "READING" = "NONE";
let backend_messages_buffer: string = "";
function reset_backend_messages_buffer(): void {
backend_messages_buffer = "";
backend_messages_state = "NONE";
}
function handle_backend_messages(data: string): void {
/* parse out messages like this:
\x1b]49;"valid JSON string here"\x07
and format and send them via our json channel.
NOTE: such messages also get sent via the
normal channel, but ignored by the client.
*/
if (backend_messages_state === "NONE") {
const i = data.indexOf("\x1b");
if (i === -1) {
return; // nothing to worry about
}
backend_messages_state = "READING";
backend_messages_buffer = data.slice(i);
//.........这里部分代码省略.........
示例4: ItemService
export function ItemService(
dimStoreService: StoreServiceType,
D2StoresService: StoreServiceType,
ItemFactory,
$q,
$i18next
): ItemServiceType {
'ngInject';
// We'll reload the stores to check if things have been
// thrown away or moved and we just don't have up to date info. But let's
// throttle these calls so we don't just keep refreshing over and over.
// This needs to be up here because of how we return the service object.
const throttledReloadStores = _.throttle(() => {
return dimStoreService.reloadStores();
}, 10000, { trailing: false });
const throttledD2ReloadStores = _.throttle(() => {
return D2StoresService.reloadStores();
}, 10000, { trailing: false });
return {
getSimilarItem,
moveTo,
equipItems
};
function equipApi(item: DimItem): (item: DimItem) => IPromise<any> {
return item.destinyVersion === 2 ? d2equip : d1equip;
}
function equipItemsApi(item: DimItem): (store: DimStore, items: DimItem[]) => IPromise<DimItem[]> {
return item.destinyVersion === 2 ? d2EquipItems : d1EquipItems;
}
function transferApi(item: DimItem): (item: DimItem, store: DimStore, amount: number) => IPromise<any> {
return item.destinyVersion === 2 ? d2Transfer : d1Transfer;
}
function createItemIndex(item: DimItem): string {
return item.destinyVersion === 2 ? d2CreateItemIndex(item) : ItemFactory.createItemIndex(item);
}
function getStoreService(item: DimItem): StoreServiceType {
return item.destinyVersion === 2 ? D2StoresService : dimStoreService;
}
/**
* Update our item and store models after an item has been moved (or equipped/dequipped).
* @return the new or updated item (it may create a new item!)
*/
function updateItemModel(item: DimItem, source: DimStore, target: DimStore, equip: boolean, amount: number = item.amount) {
// Refresh all the items - they may have been reloaded!
const storeService = getStoreService(item);
source = storeService.getStore(source.id)!;
target = storeService.getStore(target.id)!;
item = storeService.getItemAcrossStores(item)!;
// If we've moved to a new place
if (source.id !== target.id || item.location.inPostmaster) {
// We handle moving stackable and nonstackable items almost exactly the same!
const stackable = item.maxStackSize > 1;
// Items to be decremented
const sourceItems = stackable
? _.sortBy(source.buckets[item.location.id].filter((i) => {
return i.hash === item.hash &&
i.id === item.id &&
!i.notransfer;
}), 'amount') : [item];
// Items to be incremented. There's really only ever at most one of these, but
// it's easier to deal with as a list.
const targetItems = stackable
? _.sortBy(target.buckets[item.bucket.id].filter((i) => {
return i.hash === item.hash &&
i.id === item.id &&
// Don't consider full stacks as targets
i.amount !== i.maxStackSize &&
!i.notransfer;
}), 'amount') : [];
// moveAmount could be more than maxStackSize if there is more than one stack on a character!
const moveAmount = amount || item.amount;
let addAmount = moveAmount;
let removeAmount = moveAmount;
let removedSourceItem = false;
// Remove inventory from the source
while (removeAmount > 0) {
let sourceItem = sourceItems.shift();
if (!sourceItem) {
throw new Error($i18next.t('ItemService.TooMuch'));
}
const amountToRemove = Math.min(removeAmount, sourceItem.amount);
if (amountToRemove === sourceItem.amount) {
// Completely remove the source item
if (source.removeItem(sourceItem)) {
removedSourceItem = sourceItem.index === item.index;
}
} else {
// Perf hack: by replacing the item entirely with a cloned
//.........这里部分代码省略.........
示例5: push
if (!isEmpty(installLocations)) {
for (const x of installLocations) {
locationSizes[x.id] = x.sizeInfo.installedSize;
}
}
push(store, {
caves: indexBy(caves, "id"),
caveIdsByGameId: groupIdBy(caves, "gameId"),
downloadKeys: indexBy(downloadKeys, "id"),
downloadKeyIdsByGameId: groupIdBy(downloadKeys, "gameId"),
locationSizes,
});
}
const updateCommons = throttle(updateCommonsNow, 500);
export default function(watcher: Watcher) {
watcher.on(actions.preboot, async (store, action) => {
updateCommons(store);
});
watcher.on(actions.loginSucceeded, async (store, action) => {
updateCommons(store);
});
watcher.on(actions.logout, async (store, action) => {
updateCommons(store);
});
watcher.on(actions.windowFocusChanged, async (store, action) => {
示例6: FarmingService
/**
* A service for "farming" items by moving them continuously off a character,
* so that they don't go to the Postmaster.
*/
function FarmingService() {
let intervalId;
let subscription;
const glimmerHashes = new Set([
269776572, // -house-banners
3632619276, // -silken-codex
2904517731, // -axiomatic-beads
1932910919 // -network-keys
]);
// These are things you may pick up frequently out in the wild
const makeRoomTypes = [
'BUCKET_PRIMARY_WEAPON',
'BUCKET_SPECIAL_WEAPON',
'BUCKET_HEAVY_WEAPON',
'BUCKET_HEAD',
'BUCKET_ARMS',
'BUCKET_CHEST',
'BUCKET_LEGS',
'BUCKET_CLASS_ITEMS',
'BUCKET_ARTIFACT',
'BUCKET_GHOST',
'BUCKET_CONSUMABLES',
'BUCKET_MATERIALS'
];
const outOfSpaceWarning = _.throttle((store) => {
toaster.pop(
'info',
t('FarmingMode.OutOfRoomTitle'),
t('FarmingMode.OutOfRoom', { character: store.name })
);
}, 60000);
return {
active: false,
store: null,
itemsMoved: 0,
movingItems: false,
makingRoom: false,
// Move all items on the selected character to the vault.
moveItemsToVault(items: D1Item[], incrementCounter: boolean) {
return getBuckets().then((buckets) => {
const reservations: MoveReservations = {};
if (settings.farming.makeRoomForItems) {
// reserve one space in the active character
reservations[this.store.id] = {};
makeRoomTypes.forEach((type) => {
reservations[this.store.id][buckets.byId[type].type!] = 1;
});
}
return _.reduce(
items,
(promise, item) => {
// Move a single item. We do this as a chain of promises so we can reevaluate the situation after each move.
return promise
.then(() => {
const vault = D1StoresService.getVault()!;
const vaultSpaceLeft = vault.spaceLeftForItem(item);
if (vaultSpaceLeft <= 1) {
// If we're down to one space, try putting it on other characters
const otherStores = D1StoresService.getStores().filter(
(store) => !store.isVault && store.id !== this.store.id
);
const otherStoresWithSpace = otherStores.filter((store) =>
store.spaceLeftForItem(item)
);
if (otherStoresWithSpace.length) {
if ($featureFlags.debugMoves) {
console.log(
'Farming initiated move:',
item.amount,
item.name,
item.type,
'to',
otherStoresWithSpace[0].name,
'from',
D1StoresService.getStore(item.owner)!.name
);
}
return dimItemService.moveTo(
item,
otherStoresWithSpace[0],
false,
item.amount,
items,
reservations
);
}
}
if ($featureFlags.debugMoves) {
console.log(
'Farming initiated move:',
item.amount,
//.........这里部分代码省略.........
示例7: D2FarmingService
export function D2FarmingService(
$rootScope: IRootScopeService,
$q: IQService,
dimItemService: ItemServiceType,
D2StoresService: StoreServiceType,
$interval: IIntervalService,
toaster,
$i18next
) {
'ngInject';
let intervalId;
let subscription;
const outOfSpaceWarning = _.throttle((store) => {
toaster.pop('info',
$i18next.t('FarmingMode.OutOfRoomTitle'),
$i18next.t('FarmingMode.OutOfRoom', { character: store.name }));
}, 60000);
function getMakeRoomBuckets() {
return getBuckets().then((buckets) => {
return Object.values(buckets.byHash).filter((b) => b.category === 3 && b.type);
});
}
return {
active: false,
store: null,
movingItems: false,
makingRoom: false,
// Ensure that there's one open space in each category that could
// hold an item, so they don't go to the postmaster.
async makeRoomForItems(store: DimStore) {
const makeRoomBuckets = await getMakeRoomBuckets();
// If any category is full, we'll move one aside
let itemsToMove: DimItem[] = [];
makeRoomBuckets.forEach((makeRoomBucket) => {
const items = store.buckets[makeRoomBucket.id];
if (items.length > 0 && items.length >= makeRoomBucket.capacity) {
// We'll move the lowest-value item to the vault.
const itemToMove = _.min(items.filter((i) => !i.equipped && !i.notransfer), (i) => {
let value = {
Common: 0,
Uncommon: 1,
Rare: 2,
Legendary: 3,
Exotic: 4
}[i.tier];
// And low-stat
if (i.primStat) {
value += i.primStat.value / 1000;
}
return value;
});
if (!_.isNumber(itemToMove)) {
itemsToMove.push(itemToMove);
}
}
});
if (settings.farming.moveTokens) {
itemsToMove = itemsToMove.concat(store.items.filter((i) => REP_TOKENS.has(i.hash)));
}
if (itemsToMove.length === 0) {
return $q.resolve();
}
return moveItemsToVault(store, itemsToMove, makeRoomBuckets);
},
async farm(store: DimStore) {
this.makingRoom = true;
try {
// Then make room for items
await this.makeRoomForItems(store);
} finally {
this.makingRoom = false;
}
},
start(account: DestinyAccount, storeId: string) {
if (!this.active) {
this.active = true;
this.movingItems = false;
this.makingRoom = false;
// Whenever the store is reloaded, run the farming algo
// That way folks can reload manually too
subscription = D2StoresService.getStoresStream(account).subscribe((stores) => {
// prevent some recursion...
if (this.active && !this.movingItems && !this.makingRoom && stores) {
const store = stores.find((s) => s.id === storeId);
this.store = store;
this.farm(store);
}
});
//.........这里部分代码省略.........
示例8: Promise
import { SyncService } from '../storage/sync.service';
import store from '../store/store';
import { loaded } from './actions';
import { observeStore } from '../redux-utils';
import { Unsubscribe } from 'redux';
import { Settings, initialSettingsState } from './reducer';
let readyResolve;
export const settingsReady = new Promise((resolve) => (readyResolve = resolve));
// This is a backwards-compatibility shim for all the code that directly uses settings
export let settings = initialSettingsState;
const saveSettings = _.throttle((settings) => {
return SyncService.set({
'settings-v1.0': settings
});
}, 1000);
function saveSettingsOnUpdate() {
return observeStore(
(state) => state.settings,
(_currentState, nextState) => {
settings = nextState;
saveSettings(nextState);
}
);
}
let unsubscribe: Unsubscribe;
示例9: throttle
return GameFetcher;
}
return null;
}
const queueCleanup = throttle((store: IStore, window: string) => {
// TODO: figure that out multi-window
const validKeys = new Set(
Object.keys(store.getState().windows[window].tabInstances)
);
const wfs = getWindowFetchState(window);
const allKeys = union(
Object.keys(wfs.lastFetchers),
Object.keys(wfs.nextFetchReason),
Object.keys(wfs.fetching)
);
for (const k of allKeys) {
if (!validKeys.has(k)) {
logger.debug(`Cleaning up ${k}`);
delete wfs.lastFetchers[k];
delete wfs.fetching[k];
delete wfs.nextFetchReason[k];
}
}
}, 3000 /* space out cleanups */);
export default function(watcher: Watcher) {
// changing tabs? it's a fetching
watcher.on(actions.tabChanged, async (store, action) => {
const { window, tab } = action.payload;