Simple JavaScript seconds counter

November 19, 2019
/**
 * @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

posted in js by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org