/** * @author Ivan Gospodinow * @site http://ivangospodinow.com/?p=471 * * @param {callback} onUpdate * @return {callback} onStop */ export function countSeconds(onUpdate) { const start = new Date(); const interval = setInterval(() => { onUpdate(parseInt((new Date().getTime() - start.getTime()) / 1000)); }, 1000); return () => { clearInterval(interval); }; }
Usage:
/** let seconds = 0; let stopCounter = countSeconds(function(counter) { seconds = counter; }); setTimeout(stopCounter, 5 * 1000); console.log(seconds); // 2