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


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org