Skip to content

Instantly share code, notes, and snippets.

@Faizanq
Forked from edwjusti/settimeout.php
Created July 9, 2020 10:12
Show Gist options
  • Save Faizanq/435964e42244d5dacad2f7af11040293 to your computer and use it in GitHub Desktop.
Save Faizanq/435964e42244d5dacad2f7af11040293 to your computer and use it in GitHub Desktop.
setTimeout for php
<?php
class TimeoutClass extends Thread {
public function __construct(callable $cb, int $time, $args){
$this->callback = $cb;
$this->args = $args;
$this->time = $time * 1000;
}
public function run(){
usleep($this->time);
($this->callback)(...$this->args);
}
}
function setTimeout($cb, $time, ...$args){
static $count = 0;
$id = "timeout$count";
$GLOBALS[$id] = new TimeoutClass($cb, $time, $args);
$GLOBALS[$id]->start();
$count++;
}
//Basic usage
setTimeout(function(){
echo "Timeout has ended\n";
}, 2000);
//Passing arguments
setTimeout(function($x, $y){
echo "Passed $x and $y\n";
}, 2000, 25, 34);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment