javascript - increase counter by milliseconds

I am looking to enhance my JavaScript quiz counter by adding milliseconds. Currently, the quiz only tracks and displays time in seconds (stored in MySQL as a number of seconds, like 120 for 2 minutes displayed as 02:00). I now want to include milliseconds in the timer. Thank you in advance.

Below is the script:

<script type="text/javascript">
var quiz_timer = 0;

$(window).load(function(){
setInterval('run_timer()',1000 )
})

function run_timer()
{
quiz_timer++;

if(quiz_timer > 60)
{
    sec = quiz_timer%60;
    min = Math.floor(quiz_timer/60);
}
else
{
    sec = quiz_timer;
    min = 0;
}

var timer='';

if(min < 10)
timer = '0';

timer += min;

timer += ':';

if(sec < 10)
timer += '0';

timer += sec;


var timer_h = 'Time: '+timer;//+rand();
$('#quiz_timer').html(timer_h);
$('#quiz_time').val(quiz_timer);
}

function update_quiz()
{
var cnt_questions = parseInt($('#cnt_questions').val());
var cq = parseInt($('#current_question').val());
var op = $('#question_'+cq).find('input[type=radio]:checked').length;

if(op == 0)
{
    alert('You must answer on the question.');
    return false;
}

if(cq < cnt_questions)
{
    $('#question_'+cq).hide();
    $('#question_'+(cq+1)).fadeIn(1000);
    $('#current_question').val(cq+1);
    return false;
}   

$(window).unbind('beforeunload');
document.frm_quiz.submit();
}
</script>

And here's the function that inputs the data into MySQL:

function timer($quiz_timer)
{
if($quiz_timer > 60)
{
    $sec = $quiz_timer%60;
    $min = floor($quiz_timer/60);
}
else
{
    $sec = $quiz_timer;
    $min = 0;
}

$timer='';

if($min < 10)
$timer = '0';

$timer .= $min;

$timer .= ':';

if($sec < 10)
$timer .= '0';

$timer .= $sec;

return $timer;
}

Answer №1

Here is a suggested code snippet to help with your quiz timer:

<script type="text/javascript>
    var quiz_timer = 0;
    var millisecondFactor = 60;  //adjust this factor for timer accuracy
    var sec = 0;
    var min = 0;
    var hour = 0;

    $(window).load(function () {
        setInterval('run_timer()', (1000 / millisecondFactor));
    })

    function run_timer() {
        quiz_timer++;
        millisec = quiz_timer;
        
        if (millisec > millisecondFactor) {
            sec++;
            quiz_timer = 0;
        }

        if (sec > 59) {
            min++;
            sec = 0;
        }

        if (min > 59) {
            hour++;
            min = 0;
        }

        if (hour > 23) {
            hour = 0;
        }

        var timer = '';

        if (min < 10)
            timer = '0';

        timer += min;
        timer += ':';

        if (sec < 10)
            timer += '0';

        timer += sec;
        timer += ':';

        if (millisec < 10)
            timer += '0';

        timer += millisec;

        var timer_h = 'Time: ' + timer;
        $('#quiz_timer').html(timer_h);
        $('#quiz_time').val(quiz_timer);
    }

    function update_quiz() {
        var cnt_questions = parseInt($('#cnt_questions').val());
        var cq = parseInt($('#current_question').val());
        var op = $('#question_' + cq).find('input[type=radio]:checked').length;

        if (op == 0) {
            alert('You must answer the question.');
            return false;
        }

        if (cq < cnt_questions) {
            $('#question_' + cq).hide();
            $('#question_' + (cq + 1)).fadeIn(1000);
            $('#current_question').val(cq + 1);
            return false;
        }

        $(window).unbind('beforeunload');
        document.frm_quiz.submit();
    }
</script>

Answer №2

Your current approach has a notable flaw: the setInterval timing isn't accurate. A better way to handle time is by using the Date object, capturing the start time and then calculating the elapsed time within setInterval.

Below is a code snippet to help guide you in the right direction. Simply adjust the time formatting to suit your needs:

/* display the elapsed time */
function showTime(){
  var time = formatTime(Date.now() - startTime);
  document.getElementById('timer').innerHTML = time;
}

/* customize the milliseconds as desired */
function formatTime(elapsed) {
  var hours, minutes, seconds, milis;

  hours = Math.floor(elapsed/(60*60 *1000));
  elapsed -= hours * 60 * 60 * 1000;

  minutes = Math.floor(elapsed/(60*1000));
  elapsed += minutes * 60 * 1000;

  seconds = Math.floor(elapsed/1000);
  elapsed -= seconds * 1000;

  milis = elapsed;

  return 'H' + hours + ' M' + minutes + ' S' + seconds + ' F' + milis; // modify this
}

/* initiate the timer */
var startTime = Date.now();
/* updates every 10ms for accuracy */
var interval = window.setInterval(showTime, 10);

/* stop after a specified duration */
window.setTimeout(function() { window.clearInterval(interval);}, 3000);

DEMO: http://jsbin.com/EqoRezE/1/edit

PS: If Date.now() is not supported on your browser, you can use an alternate method explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Webpack encountered an error: SyntaxError due to an unexpected token {

I recently implemented Webpack for my Django and Vue project, but I encountered an error when trying to run webpack. Can anyone help me troubleshoot this issue? $ node --use_strict ./node_modules/.bin/webpack --config webpack.config.js node_modules/webp ...

Storing user responses in an array using jQuery Form

I have developed a form/questionnaire that prompts users with a series of questions. The initial question categorizes users into two groups, either trucks or cars in this scenario. Subsequently, the form delves into specific questions about the chosen vehi ...

Retrieve the data stored in a JSON object

After making an ajax call, the json object that gets returned looks like this: Object {0: "1", 1: "jake", 2: "#00ff00", tip_id: "1", tip_details: "jake", tip_color: "#00ff00"} Object {0: "2", 1: "jakee", 2: "#00ff00", tip_id: "2", tip_details: "jakee", t ...

Merge the properties of two class instances deeply

What is the best method for deep merging two instances of ES6 classes similar to lodash? The end result should be an instance of the same class with a deep merge of both instances' properties. ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

No data is being retrieved by SWR

I'm struggling to make SWR work in my code. Despite trying multiple examples, I can't seem to get it functioning properly. It's frustrating because the code looks fine and should work. I feel like I must be missing something simple. Current ...

What are the steps to resolving an Unhandled promise rejection error in a Node.js application?

I encountered an error message that I need help resolving: I am faced with an unhandled promise rejection. This issue likely occurred due to throwing inside an async function without a catch block, or rejecting a promise without handling it using .catch( ...

It looks like everything is running smoothly, but it seems like the ReactDOM.render() method is missing in action

I'm currently diving into the world of React.js and eager to build my knowledge from the basics upwards. While delving into the documentation, I stumbled upon the utilization of ReactDOM.render(element, Document.getElementById("root")), whi ...

Error Message: Incompatibility in Parameter Type Detected in UrlFetchApp Payload

When attempting to make a POST request using Google Apps Script, I encountered the error message: 'Passed parameter type mismatch: 'fields''. I attempted to resolve this issue by adding JSON.stringify(requestBody) to the payload, howev ...

What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify neces ...

I am unfamiliar with this scenario but I can utilize Axios, async/await, and TypeScript to navigate it

Having trouble creating a workflows list from an axios response Error: Argument of type 'Promise<unknown>' is not assignable to parameter of type 'SetStateAction<WorkflowForReactFlowProps[] | null>'. Here's the Axios c ...

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

What is the best way for ensuring that the test only proceeds after useEffect's update function has been executed?

function CustomApp() { let [counter, setCounter] = useState(0); useEffect(() => { setCounter(1); }, []); //<-------------------------set a checkpoint here to debug, triggered only once return counter; } // trouble-shooting ...

AngularJS directives - adjust scrollbar to correct position

In previous discussions, I mentioned this directive that I have set up. The goal is to have the user scroll up and then reload data from the backend (simulated in the directive at the bottom). My current issue is what to do with the scrollbar after reloadi ...

Can anyone guide me on how to import an npm module in Vue.js?

Looking to integrate Discord RPC into my Electron browser application, I stumbled upon this npm module. I noticed that the default Node.js method of importing it doesn't work. My application simply ignores it when done that way. const client = requi ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Boost the scrolling velocity of my sidebar using Jquery

Hello there, I am completely new to the world of web development and particularly to using JavaScript and jQuery. I am interested in learning how to adjust the speed at which my Sidebar scrolls down as the user navigates through the page. Here is the jQue ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

What is the process for transferring information from HTML to Python and then receiving the output in HTML?

I am completely unfamiliar with the connection between HTML and Python, so I am reaching out for some assistance. I hope that someone here can lend me a hand. Currently, my HTML is hosted on an Apache server, and I access the website using the address "". ...

Adjust the size of an image within a canvas while maintaining its resolution

My current project involves using a canvas to resize images client-side before uploading to the server. maxWidth = 500; maxHeight = 500; //handle resizing if (image.width >= image.height) { var ratio = 1 / (image.width / maxWidth); } else { var ...