A simple timer thats counts up the seconds you need for a Riddle

var timeStarted = 0;
var timeStopped = 0;
var secondsNeeded = 0;
var timerInterval = null;

function timerStart() {
    timeStarted = $.now();
    timerInterval = setInterval(timerCountUp, 1000);
}

function timerStop() {
    timeStopped = $.now();
    clearInterval(timerInterval);
    secondsNeeded = getSecondsBetween(timeStarted, timeStopped);
    $('#timer').hide();
    $('#result').html('Your time: ' + secondsNeeded + ' seconds');
    $('#result').show();
}

function timerCountUp() {
    $('#seconds').html(getSecondsBetween(timeStarted, $.now()));
}

function getSecondsBetween(from, to) {
    return Math.round((to - from) / 1000);
}

function onMessage(event) {
    if (event.data && event.data.riddleEvent) {
        var riddleData = event.data.riddleEvent;
        if ('object' === typeof (riddleData)) {
            if ('view-each-quiz' === riddleData.action) {
                timerStart();
            }
            if ('view-quiz-result' === riddleData.action) {
                timerStop();
            }
        }
    }
}

window.addEventListener("message", onMessage, true);

See example in action: https://examples.riddle.com/timer.php

Leave a Comment