I’m in the process of building a simple web app that allows a user to quiz his/herself on math problems. The user first chooses the type of problem she’d like to do and then how many she’d like to do.
As the user is going through the problems, I’d like to time how long it takes to complete each problem. This is the code that displays the problems on the page:
function displayMult ($i)
{
echo '<table class="basic">';
for($k=0; $k < $i; ++$k) // display problems
{
$user_response[$k] = 'user_response' . $k ;
echo '<tr>';
echo '<td>' . number_format($_SESSION['mult_one'][$k]) . '</td>';
echo '<td>'. ' x ' . '</td>';
echo '<td>' . number_format($_SESSION['mult_two'][$k]) . '</td>';
echo '<td>' . ' = <input type="text" class="field" name="user_response' . $k . '"' . 'id="u_r' . $k . '" />' . '</td>';
echo '<td id="timer_' . $k . '">test</td>';
echo '</tr>';
}
echo '</table>';
}
And this is the jQuery I have that times the user responses. The problem I’m having is that 1) I can’t figure out a way to write to always select the correct timer ID to pass into the stopwatch function and 2) stop old timer and begin new one. The current code will only time the first question and then correctly stop the timer when the user clicks on the input field for the next question.
$(document).ready(function() {
$('.field').focus(stopwatch('#timer_0'));
});
function stopwatch(container) {
var interval;
return function() {
if (interval) {
clearInterval(interval);
}
else{
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' seconds');
}, 1000);
}
};
}
I’m new to jquery so any help and insight would be greatly appreciated! Thanks in advance.
Here‘s my go at it