Search code examples
jqueryflipclock

How to get time of FlipClock?


I use flipClock.js in my site.I want get time of clock In seconds.

How to do this?

$('.clock').FlipClock(600, {
            clockFace: 'MinuteCounter',
            countdown: true,
            language: 'fa-ir',
            callbacks: {
                stop: function () {
                $('#timeout-dialog').modal({ backdrop: 'static', keyboard: false });
                }
            }
        });

Solution

  • I bet what you want to get is time delta, not just time, but time until/after smth, and in your case, time until the moment FlipClock has been instantiated + 600 seconds. In Javascript, it's usually expressed in milliseconds, by just a number. What you could do to calculate this time delta is to share the target time between two callback functions, placing the variable into outer scope:

    let timeStarted = null;
    const targetTimeDelta = 5000;
    const clock = $('#clock').FlipClock(targetTimeDelta / 1000, {
      clockFace: 'MinuteCounter',
      countdown: true,
      callbacks: {
        start: () => {
          timeStarted = new Date();
        },
        stop: () => {
          const timeStopped = new Date();
          console.log(Number(targetTimeDelta) - Number(timeStopped) + Number(timeStarted));
        }
      }
    });
    

    Here, timeStarted is first declared outside of the scope of a function passed to start callback. It makes it accessible from another scope, the scope of a function passed to stop callback. It also makes it accessible from anywhere else, and generally, globals are bad, but it's only for demo purposes here. Perhaps you know already how to encapsulate this value properly so it doesn't get redefined occasionally elsewhere in the code.

    Also, see codepen for that.