Skip to content
This repository was archived by the owner on Feb 9, 2020. It is now read-only.

Commit 311d28e

Browse files
committed
add sleep functions
1 parent f26ecec commit 311d28e

1 file changed

Lines changed: 39 additions & 1 deletion

File tree

src/pocketnode/utils/methods/Globals.js

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ void function(){
9393
* @param mode {string}
9494
* @return {Number}
9595
*/
96-
global.Math.round_php = function(value, precision = 0, mode = "ROUND_HALF_UP"){
96+
Math.round_php = function(value, precision = 0, mode = "ROUND_HALF_UP"){
9797
let m, f, isHalf, sgn;
9898
m = Math.pow(10, precision);
9999
value *= m;
@@ -191,4 +191,42 @@ String.prototype.wordwrap = function(m, b, c){
191191
j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
192192
|| c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
193193
return r.join("\n");
194+
};
195+
196+
global.assert = require("assert");
197+
198+
global.sleep = function(ms){
199+
return sleep_until(Date.now() + ms);
200+
};
201+
202+
global.sleep_until = function(ms){
203+
while(Date.now() < ms){}
204+
return true;
205+
};
206+
207+
/**
208+
* A more accurate interval
209+
* @param fn {Function}
210+
* @param interval {Number}
211+
*/
212+
global.createInterval = function(fn, interval){
213+
return new (function(){
214+
this.baseline = undefined;
215+
this.run = function(){
216+
if(this.baseline === undefined){
217+
this.baseline = Date.now();
218+
}
219+
220+
fn();
221+
222+
let end = Date.now();
223+
this.baseline += interval;
224+
225+
let nextTick = interval - (end - this.baseline);
226+
if (nextTick < 0) nextTick = 0;
227+
this.timer = setTimeout(() => this.run(end), nextTick);
228+
};
229+
230+
this.stop = () => clearTimeout(this.timer);
231+
});
194232
};

0 commit comments

Comments
 (0)