node.js - executing setTimeout function before the time if socket has received some request -
i have use case executing settimeout function after 20 seconds want function executed if socket connection front end has returned before 20 seconds. , don't want run after 20 seconds in case. how can achieve this.
the simplest scheme here put code in function use settimeout()
and, if timer still running, cancel timer , call function directly:
function dosometask() { // code here task } // schedule task run in 20 seconds // remember timer handle know it's running let timer = settimeout(() => { timer = null; dosometask(); }, 20*1000); // elsewhere in code want call function // earlier timer (if hasn't been called) if (timer) { cleartimeout(timer); timer = null; dosometask(); }
promises can offer benefit here because make sure given promise ever resolved or rejected once , can taken advantage of here. use them elegantly, i'd create little state object makes simple use.
function delayexecute(fn, t) { let obj = {state: "timer"}; let p = new promise((resolve, reject) => { obj.runnow = resolve; obj.cancel = reject; settimeout(resolve, t); }).catch(err => { obj.state = "err"; throw err; }).then(() => { fn(); obj.state = "done"; }); return obj; } function dosometask() { // code here task } let task = delayexecute(dosometask, 20*1000); // time later, run sooner (if hasn't run) // calling .runnow() method after function has run nothing task.runnow();
this same interface built without promises too. thought i'd show how leverage of one-way state transitions of promises purpose.
Comments
Post a Comment