如何编写一个应在“等待”毫秒至“限制”毫秒之间运行一次回调然后停止的函数

时间:2019-01-09 04:20:10

标签: javascript

编写一个名为limitedInterval的函数,该函数按以下顺序接受作为参数:-

  • 回调函数
  • 等待时间(以毫秒为单位)
  • 限制时间(以毫秒为单位)。

limitedInterval应该每wait毫秒(最多limit毫秒)运行一次回调,然后停止。

这就是我试图做的:

function limitedInterval(callback, wait, limit){
    setTimeout(callback, wait);  
}
var wait = 100;
var limit = 550;
function callback(){
  console.log("Repeating Callback");
}
// should log 'repeating' once per 100 ms, five times.
limitedInterval(() => console.log('repeating'), wait, limit);

我无法理解如何设置setTimeout的限制,因此该功能应每100毫秒记录一次“重复”五次

3 个答案:

答案 0 :(得分:3)

I would do something like following:

const TEMPO = 100;
const MAX = 500;
let count = 0;
const id = setInterval(() => {
  console.log('x');
  if (count > MAX) {
    clearInterval(id);
  }
  count += TEMPO;
}, TEMPO);
  1. Initialize the constants and count to provide limitation
  2. Run interval incrementing count per each iteration
  3. Break interval when count is out of MAX value

答案 1 :(得分:1)

基于setIntervalsetTimeout javascript-timer方法的方法:

const TEMPO = 100;
const MAX = 500;
const id = setInterval(() => {
  console.log('x');
}, TEMPO);
setTimeout(() => clearInterval(id), MAX);
  1. 初始化常量
  2. 给定TEMPO的运行间隔
  3. 运行超时,延迟MAX来打破间隔

答案 2 :(得分:0)

请确保在调用回调之前增加时间,否则您将调用它太多次。

const limitedInterval = (callback, wait, limit) => {
  let time = 0; 

  const handleTime = () => {
    time += wait; // increment time before checking limit & invoking callback
    if (time < limit) {
      callback();
    } else {
      clearInterval(interval);
    }
  }

  const interval = setInterval(handleTime, wait);
}