How can I make setInterval to increase speed gradually, like start from 1000 ms and than go down until 40 ms gradually in few seconds by 1 ms at a time.
Any thoughts?
This is my code:
setTimeout(function() {bonustimer = setInterval(function() { handleTimer2(rushcount); }, 40);}, 1000);
handleTimer2 = function() {
if(rushcount === -1) {
clearInterval(bonustimer);
} else {
$('.digit-wrapper').html(rushcount);
rushcount--;
}}
Set interval probably wouldn't be what you want here, as you just end up killing it and redoing it on every iteration. Much easier to use setTimeout, possibly something like this:
(function () {
var interval = 1001;
timer = function() {
--interval;
//do your thing here
if (interval >= 40) {
setTimeout(timer, interval);
}
};
timer();
})();
Also note that if you only decrease the interval by one ms at a time, from 1000 down to 40, it takes quite a while to go through all those iterations. You can always replace --interval by some other formula, like interval = interval*0.9; (to reduce by 10% each iteration) or whatever formula you want.
I guess the code by #OldGeeksGuide just stops when the interval reaches 40. Needs a little improvement ;)
(function () {
var interval = 1000;
timer = function() {
interval--;
//do your thing here
interval = interval < 40 ? 40 : interval;
setTimeout(timer, interval);
};
timer();
})();
Then you could maybe need to stop this loop by wrapping the setTimeout with some if condition ;)
Related
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();
So, I'm very, very new to Javascript, but I'm going through a problem with setInterval and clearInterval. The problem itself is to generate a number between 0 and 1. I'm supposed to console.log the answer if it's over .75, and log how many times it takes to get a number that's over .75. I figured out the Math portion, but my issue is that even though I have the setInterval correct (I think), the clearInterval isn't actually stopping it, but it keeps going, almost like an infinite loop. What am I doing wrong here?
let counter = 0
// var interval = setInterval(randomGame, 1000)
function randomGame(){
setInterval(function () {
// console.log(Math.random())
if (Math.random() > .75){
clearInterval()
}else {
console.log(counter++)
}
}, 1000)
}
You need to save a reference to the interval and then stop it using this reference, constant for example.
let counter = 0
function randomGame(){
const interval = setInterval(function () {
if (Math.random() > .75){
clearInterval(interval);
}else {
console.log(counter++)
}
}, 1000)
}
randomGame();
Clear interval is not working for an interval i use inside setTimeout().
var $scroller;
setTimeout(function() {
var div = jQuery('.module-content-slider');
$scroller = setInterval(function(){
/* interval function */
}, 25)
}, 1000);
clearInterval($scroller);
The clearInterval runs before setInterval within the "timeout" after 1 second (1000 milliseconds) is executed — effectively clearing an unset $scroller interval.
There is no what to clear.
The interval doesn't exist at clearInterval($scroller); run time.
clearInterval will be executed a second later.
Looks like your use case is to trigger interval function for every 25 ms and clear the interval after 1000 ms.
If thats the scenario then it should be
var $scroller = setInterval(function(){
/* interval function */
}, 25);
setTimeout(function() {
var div = jQuery('.module-content-slider');
clearInterval($scroller);
}, 1000);
I have two functions that display minutes and seconds. Inside the functions I'm using an IIFE with a setTimeout to calculate the time. After getting this, having a hard time figuring out how I could pause the display if pause button is clicked.
The timer works fine and displays correctly.
I realize this is probably not a good way to do it, but I spent so much time (trying to learn how to use IIFE) that I don't want to give up. If I have to, then I will scratch it.
Update - This timer will be getting input from the user. It might be 25 minutes. I want it to start counting down from there until it reaches 0, and the user able to pause at anytime.
let convertToSeconds = document.getElementById('timeValue').value * 60;
let seconds = 60;
function secondsCounter(time) {
// let flag = document.getElementById('pauseButton').value;
for (let i = seconds; i > 0; i--) {
(function(x) {
setTimeout(function() {
let remaining = seconds - x;
document.getElementById('displaySeconds').innerHTML = remaining;
console.log(remaining);
}, i * 1000);
})(i);
}
}
function counter() {
for (let i = convertToSeconds; i > 0; i--) {
(function(minutes) {
setTimeout(function() {
let remaining = Math.floor((convertToSeconds - minutes) / 60);
document.getElementById('displayMinutes').innerHTML = remaining;
console.log(remaining);
}, i * 1000);
setTimeout(function() {
secondsCounter(seconds);
}, i * 60000);
})(i);
}
secondsCounter(seconds);
}
I've tried a couple of things.
Using a flag and if statement around document.getElementById('displaySeconds').innerHTML = remaining; so if my pause button is clicked, the flag changes, and another setTimeout (10 minutes) is triggered. Doesn't stop the countdown on the DOM, it keeps going. I just wanted to see some reaction, but nothing happened. Something like:
function secondsCounter(time) {
let flag = document.getElementById('pauseButton').value;
for (let i = seconds; i > 0; i--) {
(function(x) {
setTimeout(function() {
let remaining = seconds - x;
if (flag === 'yes') {
document.getElementById('displaySeconds').innerHTML = remaining;
console.log(remaining);
} else {
setTimeout(function() {
console.log(remaining);
}, 10000);
}
}, i * 1000);
})(i);
}
}
Using a setInterval and clearInterval that didn't do anything.
Is this possible? Not sure where else to look. Thank you
You can't stop/pause a setTimeout or clearTimeout without making a reference to the timer, storing it and then calling clearTimeout(timer) or clearInterval(timer).
So, instead of: setTimeout(someFunciton)
You need: timer = setTimeout(someFunciton)
And, the timer variable needs to be declared in a scope that is accessible to all functions that will use it.
See setTimeout() for details.
Without a reference to the timer, you will not be able to stop it and that's caused you to go on a wild goose chase for other ways to do it, which is overthinking what you actually need.
In the end, I think you should just have one function that does all the counting down so that you only have one timer to worry about.
Lastly, you can use the JavaScript Date object and its get / set Hours, Minutes and Seconds methods to take care of the reverse counting for you.
(function() {
// Ask user for a time to start counting down from.
var countdown = prompt("How much time do you want to put on the clock? (hh:mm:ss)");
// Take that string and split it into the HH, MM and SS stored in an array
var countdownArray = countdown.split(":")
// Extract the individual pieces of the array and convert to numbers:
var hh = parseInt(countdownArray[0],10);
var mm = parseInt(countdownArray[1],10);
var ss = parseInt(countdownArray[2],10);
// Make a new date and set it to the countdown value
var countdownTime = new Date();
countdownTime.setHours(hh, mm, ss);
// DOM object variables
var clock = null, btnStart = null, btnStop = null;
// Make a reference to the timer that will represent the running clock function
var timer = null;
window.addEventListener("DOMContentLoaded", function () {
// Make a cache variable to the DOM element we'll want to use more than once:
clock = document.getElementById("clock");
btnStart = document.getElementById("btnStart");
btnStop = document.getElementById("btnStop");
// Wire up the buttons
btnStart.addEventListener("click", startClock);
btnStop.addEventListener("click", stopClock);
// Start the clock
startClock();
});
function startClock() {
// Make sure to stop any previously running timers so that only
// one will ever be running
clearTimeout(timer);
// Get the current time and display
console.log(countdownTime.getSeconds());
countdownTime.setSeconds(countdownTime.getSeconds() - 1);
clock.innerHTML = countdownTime.toLocaleTimeString().replace(" AM", "");
// Have this function call itself, recursively every 900ms
timer = setTimeout(startClock, 900);
}
function stopClock() {
// Have this function call itself, recursively every 900ms
clearTimeout(timer);
}
}());
<div id="clock"></div>
<button id="btnStart">Start Clock</button>
<button id="btnStop">Stop Clock</button>
can anyone see what is wrong with the following code. it's supposed to display a count down from 30 and afterwards it refreshes the page with jquery's ajax load() function.
it works fine for the first or second count down but then the timer starts too count down to fastand sometimes goes to the negative numbers and does not stop at all
what am i doing wrong?
function refreshPage(){
stopRefresh();
$('div.yui-content').load('rdPage.aspx div.yui-content', doCalculation);
}
function stopRefresh(){
clearTimeout(timer);
clearTimeout(interval);
}
var count, timer, interval;
function startTimer(){
count = 30;
timer = setTimeout(refreshPage,count * 1000);
interval= setInterval(updateTimer,1000);
}
function updateTimer(){
count --;
$('#timerSpan').text("Refreshing in " + count + "s");
}
function doCalculation(){
negativeNumberRed();
startTimer();
}
edit: added doCalculations()
try
clearInterval(interval); instead of clearTimeout(interval);
Like this:
function stopRefresh(){
clearTimeout(timer);
clearInterval(interval);
}
Add a call to "stopRefresh()" to the "startTimer()" call.
function startTimer(){
stopRefresh();
count = 30;
timer = setTimeout(refreshPage,count * 1000);
interval= setInterval(updateTimer,1000);
}
My guess is that your code is managing to start up more than one instance of the interval timer. They'll all decrement the same counter.
edit — oops - Dr. Strangelove is correct - you need to use "clearInterval()" on interval timers, and "clearTimeout()" for timeout timers. (edit again well, you probably should do that, but Chrome at least seems to stop interval timers via "clearTimeout()". Here is the jsfiddle.
I think it's better to only use the interval..
And when the count < 1 call refreshPage