当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript lodash.throttle函数代码示例

本文整理汇总了TypeScript中lodash.throttle函数的典型用法代码示例。如果您正苦于以下问题:TypeScript throttle函数的具体用法?TypeScript throttle怎么用?TypeScript throttle使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了throttle函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: return

  return (dispatch: (action: any) => any) => {
    dispatch(init());

    // Update avatar
    client.OnEnemyTargetGenderChanged((gender: Gender) =>
      client.OnEnemyTargetRaceChanged((race: Race) => {
        dispatch(onAvatarChanged(getAvatar(gender, race)));
      }),
    );
    client.OnEnemyTargetRaceChanged((race: Race) =>
      client.OnEnemyTargetGenderChanged((gender: Gender) => {
        dispatch(onAvatarChanged(getAvatar(gender, race)));
      }),
    );

    client.OnCharacterPositionChanged(_.throttle((x: number, y: number) =>
      dispatch(onCharacterPositionChanged({ x, y })), 250));

    client.OnEnemyTargetPositionChanged(_.throttle((x: number, y: number) =>
      dispatch(onTargetPositionChanged({ x, y })), 250));

    // init handlers / events
    events.on(events.clientEventTopics.handlesEnemyTarget, (player: Player) => dispatch(onCharacterUpdate(player)));

  };
开发者ID:JoelTerMeer,项目名称:Camelot-Unchained,代码行数:25,代码来源:target.ts

示例2: loadState

const configureStore = () => {
  const persistedState = loadState();

  let middleware = [thunkMiddleware];
  let newMiddleware = [];
  if (process.env.NODE_ENV !== 'production') {
    const loggerMiddleware = createLogger();
    newMiddleware = [...middleware, loggerMiddleware];
  } else {
    newMiddleware = middleware;
  }

  const store = createStore<AppState>(
    appReducer,
    // persistedState,
    applyMiddleware(...newMiddleware)
  );

  let token = getToken();
  if (token !== null) {
    store.dispatch(receiveTokenActionCreator(token.user, token));
  }

  store.subscribe(_.throttle(() => {
    saveState(store.getState());
  },                         1000));

  return store;
};
开发者ID:ttsvetanov,项目名称:polyaxon,代码行数:29,代码来源:configureStore.ts

示例3: throttle

	symbols.forEach(symbol => {
		let existingSubscriptions = this.getHandlers('price/' + symbol);
		// Price stream needs an accountId to be passed for streaming prices, though prices for a connection are same anyway
		if (!this.streamPrices) {
			this.streamPrices = throttle(this._streamPrices.bind(this, accountId));
		}
		this.off('price/' + symbol, listener);
		this.on('price/' + symbol, listener);

		if (!existingSubscriptions.length)
			this.streamPrices();
	});
开发者ID:Chegeek,项目名称:TradeJS,代码行数:12,代码来源:OANDAAdapter.ts

示例4: next

  return next => (reducer, initialState: LocalStorage, enhancer) => {
    const store: Store<LocalStorage> = next(reducer, initialState, enhancer)
    const throttleMs = 1000

    store.subscribe(
      _.throttle(() => {
        saveToLocalStorage(store.getState())
      }, throttleMs)
    )

    return store
  }
开发者ID:influxdata,项目名称:influxdb,代码行数:12,代码来源:persistStateEnhancer.ts

示例5: constructor

        constructor(private directory: string,
                    private dimensions: Dimensions,
                    private history: History) {
            super();

            this.prompt = new Prompt(directory);
            this.prompt.on('send', () => { this.execute(); });

            this.buffer = new Buffer();
            this.buffer.on('data', _.throttle(() => { this.emit('data'); }, 1000/10));

            this.parser = new Parser(this.buffer);
        }
开发者ID:RobertoUa,项目名称:black-screen,代码行数:13,代码来源:Invocation.ts

示例6: onBatch

function _makeKeyedDataBatcher<T>(onBatch: (batchData: TBySeriesId<T>) => void): (partialData: TBySeriesId<T>) => void {
  let keyedBatchAccumulator: TBySeriesId<T> = {};

  const throttledBatchCallback = _.throttle(() => {
    // Save it off first in case the batch triggers any more additions.
    const batchData = keyedBatchAccumulator;
    keyedBatchAccumulator = {};
    onBatch(batchData);
  }, 500, { leading: false, trailing: true });

  return function(keyedData: TBySeriesId<T>) {
    _.assign(keyedBatchAccumulator, keyedData);
    throttledBatchCallback();
  };
}
开发者ID:abe732,项目名称:react-layered-chart,代码行数:15,代码来源:dataActions.ts

示例7: readStatus

      .then(() => {
        devices.online = true;
        devices.current = bot;
        _.set(window, "current_bot", bot);
        readStatus()
          .then(() => bot.setUserEnv(
            { "LAST_CLIENT_CONNECTED": JSON.stringify(new Date()) }
          ))
          .catch(() => { });
        bot.on("logs", function (msg: Log) {
          if (isLog(msg) && !oneOf(BAD_WORDS, msg.message.toUpperCase())) {
            maybeShowLog(msg);
            dispatch(init({
              kind: "logs",
              specialStatus: undefined,
              uuid: "MUST_CHANGE",
              body: msg
            }));
          } else {
            throw new Error("Refusing to display log: " + JSON.stringify(msg));
          }
        });
        bot.on("status", _.throttle(function (msg: BotStateTree) {
          dispatch(incomingStatus(msg));
          if (NEED_VERSION_CHECK) {
            let IS_OK = versionOK(getState()
              .bot
              .hardware
              .informational_settings
              .controller_version, EXPECTED_MAJOR, EXPECTED_MINOR);
            if (!IS_OK) { badVersion(); }
            NEED_VERSION_CHECK = false;
          }

        }, 500));

        let alreadyToldYou = false;
        bot.on("malformed", function () {
          if (!alreadyToldYou) {
            warning(t(`FarmBot sent a malformed message. You may need to upgrade
            FarmBot OS. Please upgrade FarmBot OS and log back in.`));
            alreadyToldYou = true;
          }
        });
      }, (err) => dispatch(fetchDeviceErr(err)));
开发者ID:MrChristofferson,项目名称:Farmbot-Web-API,代码行数:45,代码来源:actions.ts

示例8: onTimeupdate

  /**
   * 监听播放中事件,每 1s 执行一次
   * @param listener 事件函数
   */
  // onTimer(listener: (
  //   /**
  //    * 进度百分比
  //    */
  //   progress: number,
  //   /**
  //    * 当前播放时间(s)
  //    */
  //   currentTime: number,
  //   /**
  //    * 总时长(s)
  //    */
  //   duration: number) => any) {
  //   /**
  //    * timeupdate 事件不是 1s 执行一次,而是在任务队列有空隙的时候执行,1s 内可能执行多次,所以并不靠谱
  //    * https://stackoverflow.com/questions/12325787/setting-the-granularity-of-the-html5-audio-event-timeupdate
  //    * 这里采用的方案是通过函数节流从而实现 1s 执行一次,实现仍然不完美
  //    */
  //   this.on('timeupdate', throttle(e => {
  //     const progress = this.$elem.duration ?
  //       // 因为如果是懒加载资源的话, play 之后才会开始播放音乐
  //       this.$elem.currentTime / this.$elem.duration * 100 : 0
  //     listener.call(this, progress, this.$elem.currentTime, this.$elem.duration || 0)
  //   }, 1000))
  //   return this
  // }

  /**
   * 监听播放中事件,会在 v8 任务队列允许的情况下尽可能快的执行
   * 也就是 1s 可能会执行多次
   * @param listener 事件函数
   */
  public onTimeupdate(listener: (
    /**
     * 进度百分比
     */
    progress: number,
    /**
     * 当前播放时间(s)
     */
    currentTime: number,
    /**
     * 总时长(s)
     */
    duration: number) => any) {
    // 为了性能做个 200ms 的节流
    this.on('timeupdate', throttle((e: Event) => {
      const progress = this.$elem.duration ?
        // 因为如果是懒加载资源的话, play 之后才会开始播放音乐
        this.$elem.currentTime / this.$elem.duration * 100 : 0
      listener.call(this, progress, this.$elem.currentTime, this.$elem.duration || 0)
    }, 200))
  }
开发者ID:linkFly6,项目名称:so,代码行数:57,代码来源:player.ts

示例9: throttle

export const startDOMDrag = (startEvent: any, onStart: (event?: MouseEvent) => any, update: (event: MouseEvent, data?: { delta?: { x: number, y: number }}) => any, stop: Function = undefined) => {

  const sx = startEvent.clientX;
  const sy = startEvent.clientY;
  const doc = startEvent.target.ownerDocument;
  let _animating: boolean;
  let _started: boolean;

  // slight delay to prevent accidental drag from firing 
  // if the user does some other mouse interaction such as a double click.
  const drag = throttle((event) => {
    if (!_started) {
      _started = true;
      onStart(event);
    }
    event.preventDefault();
    update(event, {
      delta: {
        x: event.clientX - sx,
        y: event.clientY - sy,
      },
    });
  }, 10);

  function cleanup() {
    doc.removeEventListener("mousemove", drag);
    doc.removeEventListener("mouseup", cleanup);
    if (stop && _started) stop();
  }

  doc.addEventListener("mousemove", drag);
  doc.addEventListener("mouseup", cleanup);

  return {
    dispose: cleanup,
  };
};
开发者ID:cryptobuks,项目名称:tandem,代码行数:37,代码来源:dom-drag.ts

示例10: dispatch

import axios from "axios";
import * as _ from "lodash";
import { OpenFarm, CropSearchResult } from "./openfarm";
import { DEFAULT_ICON } from "../open_farm/index";
import { HttpPromise } from "../util";
import { ExecutableType } from "./interfaces";

let url = (q: string) => `${OpenFarm.cropUrl}?include=pictures&filter=${q}`;
type X = HttpPromise<CropSearchResult>;
let openFarmSearchQuery = _.throttle((q: string): X => axios.get(url(q)), 800);

export let OFSearch = (searchTerm: string) =>
  (dispatch: Function) => {
    dispatch({ type: "SEARCH_QUERY_CHANGE", payload: searchTerm });
    openFarmSearchQuery(searchTerm)
      .then(resp => {
        let images: { [key: string]: string } = {};
        _.get<OpenFarm.Included[]>(resp, "data.included", [])
          .map(item => {
            return { id: item.id, url: item.attributes.thumbnail_url };
          })
          .map((val, acc) => images[val.id] = val.url);
        let payload = resp.data.data.map(datum => {
          let crop = datum.attributes;
          let id = _.get(datum, "relationships.pictures.data[0].id", "");
          return { crop, image: (images[id] || DEFAULT_ICON) };
        });
        dispatch({ type: "OF_SEARCH_RESULTS_OK", payload });
      });
  };
开发者ID:MrChristofferson,项目名称:Farmbot-Web-API,代码行数:30,代码来源:util.ts


注:本文中的lodash.throttle函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。