johnRivs
johnRivs

Reputation: 164

Clearing a timer without storing it in nodejs

Is there a way to clear a setTimeout without storing it in a variable and then passing it to clearTimeout?

Or somehow make setTimeout return an id instead of an object, that I would pass to clearTimeout?

Upvotes: 1

Views: 371

Answers (1)

Makubex
Makubex

Reputation: 1114

function myTimeout(f, ms) { 
    var id = setTimeout(f, ms); 
    return { 
       cancel : function() { 
          clearTimeout(id); 
       } 
    }; 
}

var t = myTimeout(somefunc, 5000);

// ...

t.cancel();

Upvotes: 1

Related Questions