Calling a function on timer reaching zero a second time - javascript

I am creating a trivia game where a timer counts down as the user attempts to guess the correct answer. I have a function setup to start my unanswered() function below when the timer reaches zero. The unanswered function runs correctly the first time the timer reaches zero but the second time the timer reaches zero I get the error:
Uncaught TypeError: unanswered is not a function at seconds.
function timerHolder() {
clearInterval(clock);
clock = setInterval(seconds, 1000);
function seconds() {
if (timer === 0) {
clearInterval(clock);
unanswered();
} else if (timer > 0) {
timer--;
$('.time').html(timer);
}
}
}
function unanswered() {
unanswered++;
$('.time').html(timer);
$('.main').append("<p class='times-up'>Time's up!</p>");
$('.first-answer').css('background-color', 'green');
$('.times-up')
.delay(2000)
.fadeOut(400);
setTimeout(questionCounter, 2000);

Related

setTimeout javascript function 'detonator timer with delay'

Write a function detonatorTimer(delay) that outputs a number to the console every second, starting with delay (integer) and ending with 'Happy New Year!' instead of 0. By setTimeout. There are errors in the code, 0 and the text is output twice.
function detonatorTimer(delay) {
console.log(delay);
if (delay > 0) {
delay --;
setTimeout(detonatorTimer, 1000, delay);
}if(delay === 0) {
console.log('Happy New Year!');
}
}
detonatorTimer(3);
You need to improve a couple of things:
Log the delay conditionally
Use else if instead of just two ifs
Remove the console.log() when invoking the function.
Try with this one:
function detonatorTimer(delay) {
if (delay > 0) {
console.log(delay);
delay --;
setTimeout(detonatorTimer, 1000, delay);
} else if(delay === 0) {
console.log('Happy New Year!');
}
}
detonatorTimer(3);

Timer shows wrong results

var seconds_lapsed = 0;
function tick() {
seconds_lapsed++;
}
function countup() {
setTimeout(function () {
if (stopped) return; // stop the loop
if (!is_paused()) {
tick();
show_time_left();
}
countup(); // <--- this is the "loop"
}, 1000);
}
This is the core of my timer. Of course I have some view to represent the result. But ticking is done here.
The problem
It shows wrong time. Have a look at this:
The timer was set for 3 hours. Twelve minutes lapsed. And the discrepancy is almost 1.5 minutes.
In the other window the timer by Google is working. This one:
So, I just compared my timer with that of google. I started them almost at once. The difference should be no more than a couple of seconds (to switch the window and press the button).
What is the reason for this, and how can I correct it?
setTimeout with an interval of 1000 does NOT run exactly after every 1 seconds.
It schedules to run after 1 second, but can be delayed with by actions running at that time.
A better way of solving this is by calculating via date difference.
I took your sample (added the missing vars/funcs) and changed the tick() function to use date diffs.
var seconds_lapsed = 0;
var startDateTime = new Date();
var stopped = false;
var is_paused = function() { return false; }
function tick() {
datediffInms = new Date() - startDateTime;
seconds_lapsed = Math.round(datediffInms / 1000);
}
function countup() {
setTimeout(function () {
if (stopped) return; // stop the loop
if (!is_paused()) {
tick();
//show_time_left();
console.log(seconds_lapsed)
}
countup(); // <--- this is the "loop"
}, 1000);
}
countup();

interval keeps firing even though clearInterval has been called

I am trying to get a function to run 10 times with a pause inbetween each run, yet when I try to it repeats the function infinite times then after 10 times it pauses, and so on. Right now this is the code with the problem:
for(i=0;i<10;i++) {
console.log(i);
interval = setInterval(function() {console.log("Function ran");}, 1000);
}
window.clearInterval(interval);
Console:0123456789Function ran["Function ran" is repeated infinite times after "9"]
interval = setInterval(function() {console.log("Function ran");}, 1000);
This line creates a new interval-instance each time, which means you have created 10 intervals. At the end of the loop interval holds the id of the last interval that was created. Hence that's the only one you're clearing, and the other ones are still running.
To cancel the interval, you need to keep track of how many times the function has been invoked. One way you can do that is as follows:
function pauseAndRepeat(delay, iterations, func) {
var i = 0;
var interval = setInterval(function() {
func();
if(++i === iterations) {
clearInterval(interval);
}
}, delay);
}
Here we have a function that defines a counter (i) in its local scope. Then it creates an interval using a function that checks the counter to see if it should call your function (func) or clear the interval when it is done. interval will have been set when the interval-handler is actually called. In this case the handler is basically a closure since it is bound to the local scope of pauseAndRepeat.
Then you can invoke the function as follows:
pauseAndRepeat(1000, 10, function() {
console.log("Function ran");
});
This will print out Function ran ten times, pausing for a second each time.
setInterval is expected to run forever, on an interval. Every time you call setInterval here, you have a new infinite loop running your function every 10s, and as others have noted you only are canceling the last one.
You may do better with chained setTimeout calls:
var counter = 0;
function next() {
if (counter < 10) {
counter++;
setTimeout(function() {
console.log("Function ran");
next();
}, 1000);
}
}
next();
This chains delayed functions, setting a timeout for the next one after each runs. You can do something similar with setInterval and cancellation:
var counter = 0;
var intervalId = setInterval(function() {
console.log("Function ran");
if (++counter >= 10) {
clearInterval(intervalId);
}
}, 1000);
In both these cases the key issue is that you trigger the next run or cancel the interval within the callback function, not in synchronous code.

Making a time counter in javascript?

I am trying to make a simple game like: www.aimbooster.com to test my javascript knowledge but I have come into a problem. Basically I want to have a timer that counts the amount of time the user has got but I can't use the setInterval method because then the program has to wait a whole second before anything else happens which is not what I want. What I want is this timer process to run in the background. I think this is commonly named as "Threading". How would I go about this?. I'd want something along the lines of:
function startTimer() {
while (stop == false) {
setInterval(function() {time++};1000);
}
}
function startGame() {
startTimer();
//MY GAME STARTS HERE
}
If I do this at the moment, the startTimer function will continually go and I won't be able to do anything else. I want startTimer to be a subproccess while the main process is the game.
while (stop === false) {
setInterval(function() {time++};1000);
}
this is a infinite loop, and you are calling setInterval infinite time and the eventloop doesn't have a chance to pop the callback to the stack to increase the time variable.
I would like to save the timer variable, and use clearInterval to stop the timer
function Game() {
}
Game.prototype.start = function() {
this.timer = setInterval(function() {
// do your stuff
}, 1000);
// start game
}
Game.prototype.stop = function() {
clearInterval(this.timer);
}
You could do something like:
function startTimer() {
setInterval(function() {while (stop == false) time++}, 1000);
}

How do I automatically refresh/run a function based on a timer?

How can I make a function, and have it run/refresh every (second) once in a while based on a timer? I'm trying to run a function and it needs to be updated to check if a parameter is checked.
function checkTime() {
if(document.getElementById("time").innerHTML === "12:00:00 PM") {
alert("It's noon!");
}
}
This can be accomplished by using setInterval(). I am using something similar for this; I made a timer that shows the time that my period ends (in school) and also shows the current time, and when the time matches the period ends time, it should change to the next period automatically. With your example, you can do something like this:
//init function
function checkTime() {
//check if its noon
if(document.getElementById("time").innerHTML === "12:00:00 PM") {
//alert
alert("It's noon!");
}
}
//set the interval
setInterval(function() {
//execute code
checkTime();
}, /* every 5 seconds, or 5000 milliseconds */ 5000);

Categories

Resources