-
Notifications
You must be signed in to change notification settings - Fork 68
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #127 from imddc/main
feat: add repeatExecute api
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |