timer with delay, reset and restart? jQuery - javascript

So I basically have a timer which counts 1 number every 4 seconds.
It stops when it hits 10.
Q: How do i make it so that the timer stops at 10 for a couple of seconds, then starts counting again at 1?
var i = 8;
setInterval( increment, 4000);
function increment(){
if(i<=10)
{
console.log(i);
$('.increase').html('').append(i);
i++;
}
}
JSfiddle: http://jsfiddle.net/0t3s8erj/

Use the else!
var counter = 0
function increment () {
counter++
if (counter <= 10) {
console.log(counter)
} else {
clearInterval(incrementInterval)
setTimeout(function () {
incrementInterval = setInterval(increment, 4000)
}, 10000)
}
}
incrementInterval = setInterval(increment, 4000)

You can do it like this where you run an interval timer until you get to the max count, then you clear that timer and start a new timer for the amount of time you want to pause and then when that delay timer fires, you call your function again to start it all over.
Here's a working code snippet (I set the times short here for demo purposes, but you can set them to whatever you want):
function runTimer(selector, start, end, interval, delay) {
var cntr = start;
$(selector).html(cntr);
var timer = setInterval(function() {
++cntr;
$(selector).html(cntr);
if (cntr >= end) {
clearInterval(timer);
setTimeout(function() {
runTimer(selector, 1, end, interval, delay);
}, delay);
}
}, interval);
}
runTimer('.increase', 8, 10, 300, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="increase">8</span>/10

Related

How can I postpone setInterval if a condition is met?

This is my script:
var find = setInterval(function() {
if (document.getElementsByClassName('RDlrG Inn9w iWO5td')[0]) {
if (document.getElementsByClassName('w1OTme')[0]) {
window.open(document.getElementsByClassName('w1OTme')[0].href);
//here I call the setTimeout function for my SetInterval
}
}
}, 2000);
This is a Tampermonkey script I am developing for Google Calendar.
I want to set a timeout function on my find function aka setInterval function so it doesn't spam the window.open function.
In short:
Is there a way I could set a Timeout function on setInterval function which is called from my setInterval function?
If yes, how so?
You can't pause the interval of a setInterval, but you can stop it and start it again after some time.
let find = null;
function intervalFunc() {
if (condition) {
// Do some operations which should not be repeated for the next 30 seconds
// Clear current interval
clearInterval(find);
// Schedule to start the setInterval after 30 seconds.
setTimeout(function() {
find = setInterval(intervalFunc, 2000);
}, 30000 - 2000);
// ^
// Subtracting the interval dalay to cancel out the delay for the first invocation.
// (Because the first invocation will also wait for 2 seconds, so the pause would be 32 seconds instead of 30)
}
}
// Start the initial setInterval
find = setInterval(intervalFunc, 2000);
Here is a working example:
let count = 0;
const intervalDelay = 200;
const pauseDelay = 3000;
let find = null;
function intervalFunc() {
count++;
console.log('check', count);
if (count >= 5) {
count = 0;
console.log('Pausing for ' + (pauseDelay / 1000) + ' seconds');
clearInterval(find);
setTimeout(function() {
find = setInterval(intervalFunc, intervalDelay);
}, pauseDelay - intervalDelay);
}
}
find = setInterval(intervalFunc, intervalDelay);

can't stop this recursive settimeout function in nodejs

I made this recursive set timeout function to send time for each game room but when the time finishes i cannot stop the function. i tried the clear timeout but it did not help so if anyone would help me.
setTimeout(function GameTime() {
io.in(Rooms[picked].name).emit('PlayTime', timeleft);
timeleft.x--; // HERE WHERE I DECREMENT THE TIME
setTimeout(GameTime, 1000)
}, 1000)
Assuming you're not stopping the loop, you has to stop it using the function clearTimeout.
A better approach for your scenario is using the function setInterval:
var x = 3;
var intervalId = setInterval(function GameTime() {
//io.in(Rooms[picked].name).emit('PlayTime', timeleft);
//timeleft.x--; // HERE WHERE I DECREMENT THE TIME
x--;
if (x < 0) {
clearInterval(intervalId);
console.log('finished!');
return;
}
console.log('looping!');
}, 1000)
You need a reference to the setTimeout you want to clear:
let timeoutId, gameTimeoutId
timeoutId = setTimeout(function GameTime() {
console.log('GameTime')
gameTimeoutId = setTimeout(GameTime, 1000)
}, 1000)
setTimeout(function GameTime() {
clearTimeout(timeoutId)
clearTimeout(gameTimeoutId)
}, 5000)
This snippet will call GameTime each 1 second and after 5 seconds it removes the interval loop
As an alternative to this is to use setInterval, this will simplify you code considerable:
const intervalId = setInterval(() => {
console.log('GameTime')
// do stuff
}, 1000)
setTimeout(() => {
clearInterval(intervalId)
}, 5000)

Unable to cancel setInterval

I am making a Javascript timed quiz with 10 questions to be answered in 60 seconds. It works fine if the contestant attempts the question in 50 to 60 seconds, but if he does it in a shorter time and restarts the quiz the timer runs at double the speed. Possibly the earlier timer isn't getting cleared. Here is the script:
$(window).ready(function() {
$('#fblock').hide();
$('#sblock').show();
$('#qblock').hide();
$('.startquiz').click(function() {
qsi = 0;
score = 0;
showq(0);
$('#fblock').hide();
$('#sblock').hide();
$('#qblock').show();
var secs = 0;
var id = setInterval(function() {
secs++;
console.log(secs);
document.getElementById("timer").innerHTML++;
if (secs > 60) {
clearInterval(id);
$('#result').html(score);
$('#qblock').hide();
$('#fblock').show();
}
}, 1000);
});
$('.restartquiz').click(function() {
$('#fblock').hide();
$('#sblock').show();
$('#qblock').hide();
document.getElementById("timer").innerHTML = 0;
});
});
For me it looks like the only time the interval gets canceled is, when the "timer" (secs) actually exeeds the number of 60.
The doubled speed could be explained by secs++ which (after restarting the quiz) gets executed two times (once per started interval).
Try canceling the interval in the function that gets executed when pressing the .restartquiz-Button.
This could look like something like that (untested):
var interval = null;
$(window).ready(function() {
$('#fblock').hide();
$('#sblock').show();
$('#qblock').hide();
$('.startquiz').click(function() {
qsi = 0;
score = 0;
showq(0);
$('#fblock').hide();
$('#sblock').hide();
$('#qblock').show();
var secs = 0;
interval = setInterval(function() {
secs++;
console.log(secs);
document.getElementById("timer").innerHTML++;
if (secs > 60) {
clearInterval(interval);
$('#result').html(score);
$('#qblock').hide();
$('#fblock').show();
}
}, 1000);
});
$('.restartquiz').click(function() {
$('#fblock').hide();
$('#sblock').show();
$('#qblock').hide();
clearInterval(interval);
document.getElementById("timer").innerHTML = 0;
});
});

System clock timer with Javascript

I'm trying to use the system clock to make a simple animation in Javascript. I want to cycle through an array so that [0],[1],[2]... are called at 500ms intervals. Using an example from a previous Stack Overflow answer I was experimenting with this code snippet:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = (time*1000)-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},500); // the smaller this number, the more accurate the timer will be
}
The function is then called using the following approach:
timer(
5, // seconds
function(timeleft) { // called every step to update the visible countdown
console.log(3 - timeleft );
},
function() { // what to do after
console.log("Timer complete!");
}
);
This produces, 0,1,2,3,"Timer Complete". However, I can't figure out how this can be called at 500ms intervals. I've tried tweaking the numbers, but I realize that I don't fully understand how this function works. Is it possible to adjust this, or are there some hard coded browser functions that are being called here on the 1s interval?
I tried changing all of the values to the following:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = (time*500)-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/500));
},500); // the smaller this number, the more accurate the timer will be
}
timer(
5, // seconds
function(timeleft) { // called every step to update the visible countdown
console.log(5 - timeleft );
},
function() { // what to do after
console.log("Timer complete!");
}
);
This now produces:
2
3
4
5
Timer complete!
at what I think are 500ms intervals, but I'm not sure. Changing the value 5 in 5 - timeleft also does strange things to the speed at which this runs.
I believe you're overcomplicating this. If all you want is to display each item from an array every 500ms, use a regular counter, not timestamps and rounding:
function timer(myArray) {
var counter = 0;
var interval = setInterval(function() {
// There are still items we want to display
if(counter < myArray.length) {
console.log(myArray[counter]);
// We have displayed all
} else {
console.log('Finished');
clearInterval(interval);
}
// Increment counter
counter++;
}, 500); // 500 here is the interval in msec
}
var arr = ['Item 0', 'Item 1', 'Item 2', 'Item 3'];
timer(arr);
http://jsfiddle.net/AE58p/

Timer counting faster on second run

I am working on a simple game right now. its almost done except for the timer has a glitch in it and I can't figure out whats doing it. when you push a button, an HTML5 text on the canvas starts to count down from 35 to 0. On the first run it's fine. But if you choose to play again with out refresh the timer starts to countdown faster. here is the code.
var timer = 35;
ctx.fillText("Countdown: " + timer, 320, 32);
function resetReggie(){
reggie.x = canvasWidth / 2;
reggie.y = canvasHeight / 2;
}
//Starts Timer for Timed Game
function timedMsg()
{
resetReggie();
ballsCaught = 0;
timer = 35;
alert('Pick up as many as you can in ' + timer + ' seconds');
countDown();
var t=setTimeout(function() {
var again = confirm("TIMES UP! You Gathered " + ballsCaught + " Balls! Play Again?");
if (again === true){
timedMsg();
resetReggie();
}
if (again === false){
resetReggie();
ballsCaught = 0;
timer = 35;
}
}, timer * 1000);
}
function countDown() {
if (timer != 0){
timer-=1;
setTimeout('countDown()', 1000);
}
}
I think the problem is in the line
}, timer * 1000);
where you have a value that is at most 34 at the time 'timer' is evaluated to set the timeout. Because you initialize it to 35 but then call countDown() which decreases it to 34, then you have a call to confirm() which might let 'timer' decrease even more. As a result the subsequent call to timedMsg() happens a little too soon causing countDown() to be called twice as often. Try the following (I ran it in node) and then change the 4 to 6.
function countDown() {
console.log("Countdown: " + timer, 320, 32);
if (timer != 0) {
timer -= 1;
setTimeout(countDown, 1000);
}
}
function timedMsg() {
timer = 5;
countDown();
var t=setTimeout(function() {
timedMsg();
}, 4 * 1000);
}
timedMsg();
As mentioned in my comment, each time you start a new game, it appears you are decreasing the timeout value. As a result, this reduces the time each time.
Try this:
var timeout = currentTime = 5;
var int = setInterval(function() {
​console.log(currentTime);
currentTime--;
if(currentTime < 0) {
var again = confirm('Play again?');
if(again) {
currentTime = timeout;
}
else {
clearInterval(int);
}
}
}, 1000);​
http://jsfiddle.net/gRoberts/CsyYx/
Look at your console (F12 in Chrome), or update the code to write to the browser to see it working ;)

Categories

Resources