编写一个名为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毫秒记录一次“重复”五次
答案 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);
count
to provide limitationcount
per each iterationMAX
value答案 1 :(得分:1)
基于setInterval
和setTimeout
javascript-timer方法的方法:
const TEMPO = 100;
const MAX = 500;
const id = setInterval(() => {
console.log('x');
}, TEMPO);
setTimeout(() => clearInterval(id), MAX);
TEMPO
的运行间隔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);
}