Skip to content

实现一个函数, 可以间隔输出

js
function createRepeat(fn, repeat, interval) {}

const fn = createRepeat(console.log, 3, 4);

fn('helloWorld'); // 每4秒输出一次helloWorld, 输出3次

可以使用 JavaScript 中的定时器函数 setInterval 来实现,具体如下:

js
function createRepeat(fn, repeat, interval) {
	let count = 0;

	return (param) => {
		const timer = setInterval(() => {
		    fn(param)
		    count++;
		    if (count >= repeat) {
		      clearInterval(timer);
		    }
	    }, interval * 1000);
	}
}