Skip to content

Commit

Permalink
Merge pull request #127 from imddc/main
Browse files Browse the repository at this point in the history
feat: add repeatExecute api
  • Loading branch information
chenbimo authored Sep 5, 2024
2 parents 326c92d + 4a585eb commit ab8c290
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
38 changes: 38 additions & 0 deletions lib/helper/repeatExecute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import isFunction from '../is/function.js';

/**
* 重复执行函数
* @alias yd_helper_repeatExecute
* @category helper
* @param {Function} fn 获取字段的方式
* @param {number} times 执行次数
* @param {number} delay 执行间隔
* @author imddc <https://github.com/imddc>
* @example
* yd_helper_repeatExecute(() => {console.log('execute!')}, 5, 1000)
* // 打印五次`execute!` 每次间隔1000ms
*/
export default async (fn, times, delay) => {
if (!isFunction(fn)) {
throw new Error('fn must be a function');
}

if (times === 0) {
return;
}

let counter = 0;
async function execute() {
fn();
counter++;

if (counter < times) {
await new Promise((resolve) => {
setTimeout(resolve, delay);
});
await execute();
}
}

await execute();
};
17 changes: 17 additions & 0 deletions lib/helper/repeatExecute.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest';
import repeatExecute from './repeatExecute.js';

describe('repeatExecute', () => {
it('should work well', async () => {
let sum = 0;
await repeatExecute(
() => {
sum += 1;
},
5,
300
);

expect(sum).toBe(5);
});
});

0 comments on commit ab8c290

Please sign in to comment.