Как реализовать функцию, подобную дроссельной заслонке, но без потери времени между вызовами - PullRequest
0 голосов
/ 27 марта 2020

Я хотел бы реализовать вспомогательную функцию, такую ​​как газ loda sh, но которая вызывает переданный обратный вызов, только если последний вызов завершился (и если нет, задерживает новый вызов до тех пор), вместо наличия правила как "один вызов каждые х миллисекунд".

Какой лучший подход здесь? Спасибо.

Ответы [ 3 ]

0 голосов
/ 27 марта 2020

попробуйте использовать логическую переменную, такую ​​как

var running = false;

, используйте setInterval или аналогичную функцию и поставьте условие if(!running){} для выполнения операторов. если оператор будет запущен, сделайте running = true.

0 голосов
/ 27 марта 2020

Наконец-то сработало:

class Scheduler {
  private readonly stack: Function[] = [];

  private enqueue(task: Function) {
    if (this.stack.length < 2) this.stack.push(task);
    else this.stack[1] = task;
  }

  private dequeue() {
    if (this.stack.length) {
      const task = this.stack.shift()!;
      task();
      defer(() => this.dequeue());
    }
  }

  run(task: Function) {
    this.enqueue(task);
    defer(() => this.dequeue());
  }
}

// Usage :

const scheduler = new Scheduler()

// Very frequent call :

scheduler.run(() => { /* your heavy task */ })
0 голосов
/ 27 марта 2020

Итак, в конечном итоге вы хотите поставить в очередь свои вызовы функций и вызывать их из стека.

// keep a stack of inputs for the function calls
var stack = [], 
    timer = null;

function process() {
    var item = stack.shift();
    //
    // process the item here
    //
    if (stack.length === 0) {
        clearInterval(timer);
        timer = null;
    }
}
// every time you call the function on event. instead of calling the processing function
// call this to add it in a queue
function queue(item) {
    stack.push(item);
    if (timer === null) {
        timer = setInterval(process, 500);
    }
}

Эту функцию также можно использовать для нескольких типов вызовов. // использовать элемент как решающий фактор

// keep a stack of inputs for the function calls
var stack = [],
  timer = null;
function reset(item){
    // reset item here
}
function process() {
  var item = stack.shift();
  //
  // process the item here
  //
  switch (item.call) {
    case 'reset':
         reset(item);
      break;
    case 'stop':
//         stop(item);
      break;
    default:
      // code block
      // deal with it
  }
  if (stack.length === 0) {
    clearInterval(timer);
    timer = null;
  }
}
// every time you call the function on event. instead of calling the processing function
// call this to add it in a queue
// for hybrid calls 
// use item = {'call': 'reset', 'data': item}
function queue(item) {
  stack.push(item);
  if (timer === null) {
    timer = setInterval(process, 500);
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...