Skip to content

Commit fd85fcf

Browse files
committed
Add Function.delay function
1 parent e2003ea commit fd85fcf

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/Function/delay.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
namespace _;
13+
14+
/**
15+
* Invokes `func` after `wait` milliseconds. Any additional arguments are
16+
* provided to `func` when it's invoked.
17+
*
18+
* @category Function
19+
*
20+
* @param callable $func The function to delay.
21+
* @param int $wait The number of milliseconds to delay invocation.
22+
* @param mixed[] $args
23+
*
24+
* @return int the timer id.
25+
* @example
26+
* <pre>
27+
* delay(function($text) {
28+
* echo $text;
29+
* }, 1000, 'later');
30+
* // => Echo 'later' after one second.
31+
* </pre>
32+
*/
33+
function delay(callable $func, int $wait = 1, ...$args): int
34+
{
35+
usleep($wait * 1000);
36+
37+
$func(...$args);
38+
39+
return 1;
40+
}

tests/Function/DelayTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
use function _\delay;
13+
use PHPUnit\Framework\TestCase;
14+
15+
class DelayTest extends TestCase
16+
{
17+
public function testDelay()
18+
{
19+
$a = 1;
20+
$time = microtime(true);
21+
delay(function ($increment) use(&$a) {
22+
$a += $increment;
23+
}, 20, 2);
24+
25+
$this->assertSame(3, $a);
26+
$this->assertTrue(((microtime(true) - $time) * 1000) > 20);
27+
}
28+
}

0 commit comments

Comments
 (0)