I created a quiz application using PHP. In that application I display one question per page. When user clicks on the next button, it displays the next question, one chosen randomly from database. So for that I want to display time.
But my problem is:
I want to display a timer from starting only seconds. When user clicks on the next button, first question timer is going to be stored in database and the timer will start(from 00:00) for the second question.
I tried a lot, but I don't have any idea how to do this.
It is better to use window.setInterval() in order for the timer to not rely on the system time. .setInterval will fire every n milliseconds. You can just increment using that
You can have:
var secondsCounter = 0;
function quizTimer(){
secondsCounter++;
}
window.setInterval(quizTimer, 1000);
Then you can display the time easily by using
myTimerElement.innerHTML = "Seconds Passed: " + secondsCounter;
Now you just have to do a little tweaking to make it appear in time format MM:SS
it could be
myTimerElement.innerHTML = minutesCounter + " : " + secondsCounter;
now just do some formatting methods or conditions to make the counter variables display two digits.
EDIT:
Check this snippet:
var secondsCounter = 0;
var startTime;
function restartTimer(){
secondsCounter = 0;
window.clearInterval(startTime);
startTime = window.setInterval(quizTimer, 1000);
}
function quizTimer(){
secondsCounter++;
document.getElementById('timer').innerHTML = "Seconds Passed: " + secondsCounter;
}
document.getElementById('btnsub').addEventListener('click', restartTimer);
<span id='timer'></span>
<button id='btnsub'>Submit</button>
Related
I wanted to make a website. rough principle:
The user can input time and rounds using the prompt() function.
A loop that prints a text runs so often how the user entered it and between every print I want the loop to pause for the time, the user entered before.
I looked up lots of posts but there is nothing useful.
In the script, I used a sleep function which waits so long until the input time is equal to the current time, almost like the setTimeout() function but both don't work for me since it doesn't pause the whole script entirely. The script sleeps the time entered by user multiplied by the number of rounds and then it prints all the texts at the same time.
I want a function that can actually pause the loop and after the entered time it continues.
Sorry for bad English, need help
var textPara = document.getElementById("para");
var rounds = prompt("How often");
var count = 1;
do {
textPara.textContent += "Round " + count;
count++;
sleep(5000);
} while (count <= rounds)
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
<p id="para"></p>
IS this what you're wanting?
var textPara = document.getElementById("para");
var rounds = 5; // prompt("How often");
var count = 1;
var interval = 500;
function update(){
textPara.textContent += "Round " + count;
count++;
if (count <= rounds){setTimeout(update,interval)}
}
update();
<div id="para"></div>
In your original code, the event loop is blocked in the while loop and immediately moves on to the ensuing code, which triggers another sleep... and so the browser screen only updates once all the sleeping is over (the textContent value has updated multiple times in JS, but the browser doesn't show this).
In this example, the update function puts a new (recursive) call to itself in the future, but the event loop and browser are free to do updates in the interim, so we see the updates.
setTimeout can be useful this way even with an interval of zero to allow screen updates etc.
I have a timer mainly using javascript, currently the start/stop functionality works fine. When user hits "Stop" button it takes the time from the #time element, converts it to decimal value and updates the hidden #counter element. For example an 1 and a half hours would be converted to 1.50
My problem is I also want to allow users to edit the time manually so I have a little plugin that was created to do allow for this.
There are 2 problems:
If a user manually adds their time by double clicking the element and adjusting then were to hit save, the #counter element has not be updated so it is submitting the time as 0.
If a user were to manually set their time and then hit the Start button, the clock starts from 0 instead of the time they specified.
I have a JS Fiddle available here: https://jsfiddle.net/pkj7wyLu/
Toward the bottom of the JS block in that fiddle you will see:
//implement plugin
$('span#time').editable().on('editsubmit', function (event, val) {
console.log('text changed to ' + millisecondsToHours(val));
});
which I believe is the event that fires each time the user manually enters time.
Question: How can I make it where when someone manually enters time that it automatically updates the #counter field with the converted values and if they press start it starts from that time?
What I tried: I tried playing with the format(Time) function and have it currently trying to print the value to the console but I am not getting results
I have created an override method on your clsStopwatch class, like so:
this.override = function(time) {
lapTime = time;
}
This will update the lapTime, passing in a time in milliseconds. To do this I created a new function which accepts a string:
function stringToMilliseconds(str) {
var a = str.split(':'); // split it at the colons
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
return seconds * 1000;
}
This will return the number of milliseconds from the edited string in the id #time element span.
Finally, I updated the submit editable event to call the override:
$('span#time').editable().on('editsubmit', function (event, val) {
x.override(stringToMilliseconds(val));
});
Here is the updated JSFiddle
Hope that helps.
I need to create a special kind of script.
I want to show a message at certain times of the day. I've tested the code in Firebug Console and it works. The code is:
//Getting the hour minute and seconds of current time
var nowHours = new Date().getHours() + '';
var nowMinutes = new Date().getMinutes() + '';
var nowSeconds = new Date().getSeconds() + '';
var this_event = nowHours + nowMinutes + nowSeconds;
//172735 = 4PM 25 Minutes 30 Seconds. Just checked if now is the time
if (this_event == "162530") {
window.alert("Its Time!");
}
I feel that the Script is not running every second. For this to work effectively, the script has to be able to check the hour minutes and second "Every Second". I'm not worried about the performance, I just have to be accurate about the timing (to the second).
How do I do this?
Of course the script isn't running each second, GM-scripts run once when the document has been loaded.
Calculate the difference between the current time and the target-time and use a timeout based on the difference:
var now=new Date(),
then=new Date(),
diff;
then.setHours(16);
then.setMinutes(15);
then.setSeconds(30);
diff=then.getTime()-now.getTime();
//when time already has been reached
if(diff<=0){
window.alert('you\'re late');
}
//start a timer
else{
window.setTimeout(function(){window.alert('it\'s time');},diff);
}
Javascript doesn't guarantee your timeouts and other such events fire exactly on-time.
You should compare two Date objects using >= and remove the timeout or what ever other method you're using for tracking the time inside the matching if (and then reset it if necessary).
For more details see: https://stackoverflow.com/a/19252674/1470607
Alternatively you can use string comparison (but with caveats): https://stackoverflow.com/a/6212411/1470607
I'm currently developing a small game for a class using Crafty, and our game requires the passage of time. To give context, it's a tamagotchi-like game where the player controls a creature and feeds it, grooms it, etc., when required, so we need to measure time for things such as "every five minutes the creature will be hungry" or "after a certain amount of time (say, 20 minutes) the creature will die of natural causes and the game will end". My problem is that I'm not sure what is the best way to go about this. Should I use setInterval? setTimeout? My own timer class? I don't know what's the most common solution for instances like these. So far I've tried the first two options without successful results.
I also tried looking for any crafy functions for time; and the closest I could find was
Crafty.bind("EnterFrame", function() { ... }), so I could 'manipulate' time frame by frame, but this didn't work either. Thanks in advance.
When the game starts, get a timestamp with new Date().getTime(), and keep it in a variable. On regular intervals (you can use setInterval), compare that with the current timestamp, and act according to how much time has passed.
I suggest building an array with the timed events, and checking its elements from the timer callback. Something like this:
var startTime = new Date().getTime();
// List of timed events
// (times are in milliseconds)
var events = [
{ time: 5000, text: "do something after 5 secs"},
{ time: 10000, text: "do something after 10 secs"},
{ time: 20000, text: "do something after 20 secs"}
];
// Check for events every second
setInterval(function() {
var timePassed = new Date().getTime() - startTime;
console.log("passed: " + timePassed + " milliseconds");
// Check all events
for(var i=events.length-1; i>=0; i--) {
// If an event has expired, remove it from the list,
// (and do whatever tou need to do)
if(events[i].time <= timePassed) {
// log the event text to the console
console.log(timePassed + "ms passed. " + events[i].text);
// remove from array
events.splice(i, 1);
}
}
}, 1000);
DEMO (open your browser console to see the output).
Rather than use the single timestamp as in bfavartto's answer, you could expand that to set multiple, dynamic timestamps in a "time" array (or object) or even simply as individual variables and then update them as actions occur.
A simple version would be something like:
// Initialize the variables at the beginning of the game
var lifeStamp = new Date().getTime();
var foodStamp = lifeStamp ;
var groomStamp = lifeStamp ;
function feed() {
/*** Do feed-realted stuff here ***/
// reset the "feed" timestamp
foodStamp = new Date().getTime();
}
function groom() {
/*** Do groom-realted stuff ***/
// reset the "groom" timestamp
groomStamp = new Date().getTime();
}
That way, you could keep your intervals, but reset them by resetting the timestamps that your intervals compare against for different types of actions. At the same time, the "life" timestamp would stay the same, while the other ones changed.
Edit: Re-looking at bfavartto's answer, it looks like you would need to store off and "original" list of any action-specific events as well, so that, as you reset the timestamps, you could reset the actions that go with them.
Edit #2: One more thing . . . if you want these creatures to last past the current page load, you might want to look into using cookies or HTML5's LocalStorage to store these timestamps. That would allow you to (practically) use much longer intervals, as well as let users leave the page and come back to pick up where they left off (though, I'd imagine that there would be a considerable amount of other data that would need to be stored as well, in order to allow users to leave and come back).
I am developing a test engine web application. Users will be give some amount of time to answer questions. I want to create a countdown clock after which the test is finished. I'm using javascript right now but facing problems of refresh and back button in the browser.
Following is the javascript:
<script>
function countDown (count) {
if (count > 0) {
var hours = Math.floor(count/3600)
var minutes = Math.floor(count/60) - (hours*60)
var seconds = count - (minutes * 60) - (hours*3600)
var d = document.getElementById("countDiv");
d.innerHTML = hours + ":" + minutes + ":" + seconds;
else
document.location = "test_finished.html";
}
countDown(<%=#totaltime%>);
</script>
How can i disable the refresh and back button or some other workaround??
You cannot enforce such things using JavaScript.
One way would be to have records in the database which hold the test start date time in it, once a user starts a test the start time is set, upon loading the initial timer value is calculated using it, so you can have back and refresh working fine and the countdown timer always being accurate.