How to speed up the count down? - javascript

I am working on a basic countdown using Javascript where, the countdown starts from 0 and then ends till 24 as thats the idea of the countdown, I want to end it at 24. Here's the code:
var count=0;
var counter=setInterval(timer, 50); //1000 will run it every 1 second
function timer()
{
count=count+1;
if (count >= 24)
{
clearInterval(counter);
//counter ended, do something here
document.getElementById("countdown").innerHTML=24 ;
return;
}
//Do code for showing the number of seconds here
document.getElementById("countdown").innerHTML=count ; // watch for spelling
}
Now the thing is that if you notice this, the countdown happens very fast, this is the intended effect. However the question is this, Is there a way to have a smooth easing type effect, where the countdown starts slowly and then speeds up by the end ? How to achieve that effect ?
Thanks for your response.
EDIT: Here is the fiddle, to see the countdown in action and to gain a deeper insight.

You'll need to use setTimeout instead of setInterval and another variable for setTimeout.
var count=0;
var speed = 1000;
timer();
function timer()
{
count++;
//Do code for showing the number of seconds here
document.getElementById("countdown").innerHTML=count ; // watch for spelling
if (count >= 24)
{
return;
}
speed = speed / 6 * 5; // or whatever
setTimeout(timer, speed);
}
Fiddle: http://jsfiddle.net/4nnms1gz/2/

Use a timeout which runs only once then add extra time and run the timeout again until you reach 24.
var count=0;
var ms = 200;
var step = 5;
var counter=setTimeout(timer, ms); //1000 will run it every 1 second
function timer()
{
count=count+1;
if (count <= 24)
{
//Do code for showing the number of seconds here
document.getElementById("countdown").innerHTML=count ; // watch for spelling
ms = ms - step;
counter = setTimeout(timer, ms);
}
}

Using setTimeout will give you more control on your counter.Here is a working example where you can handle the speed of your counter.It will give you a time increase of 30ms to 70ms to each call to time function
var count=0;
var loop=1000;
var interval;
var text=document.getElementById('countdown');
var range=document.getElementById('range');
var btn=document.getElementById('btn');
var span=document.getElementById('val');
range.addEventListener('change',function(e){
span.innerHTML=range.value+' ms';
});
btn.addEventListener('click',function(e){
timer(parseInt(range.value));
});
function timer(time)
{
console.log(time);
if (count < 24)
{
count=count+1;
text.value=count;
loop-=time;
interval=setTimeout(function(){
timer(time);
},loop);
if(count>=24){
clearTimeout(interval);
return;
}
}
}
<input type='text' id='countdown' value='0'></br>
<input type='range' id='range' max='70' min='30' value='30' >increase by:<span id='val'></span></br>
<input type='button' value='start' id='btn' ></br>

Related

javascript Bootstrap Progressbar fill in 10 seconds

I have a Progressbar in Bootstrap that fills every 1 sec 10% of the progressbar.
The problem is, that the site lags over the whole browser (chrome), but why?
That's my code that fills the Progressbar
var isPaused = false;
$(window).scroll(function(){
var ScrollTop = parseInt($(window).scrollTop());
if (ScrollTop > 10) {
isPaused = true;
} else {
isPaused = false;
}
});
var timeleft = 1;
var table_updated = 0;
var timeleft_zahl = 10;
var tick = function() {
if(!isPaused && $("#page-1").hasClass("active") && !$(".modal").hasClass("show")) {
document.getElementById("progressBar").style.width = timeleft*10+"%";
document.getElementById("refreshcountdown").innerHTML = timeleft_zahl-1;
timeleft += 1;
timeleft_zahl -= 1;
if(timeleft >= 11){
notificationcheck();
timeleft = 0;
timeleft_zahl = 11;
if(table_updated >= 10) {
location.reload();
table_updated = 0;
} else {
get_table_data(1);
table_updated += 1;
}
}
}
}
timer = setInterval(tick, 1000);
So it's just simple.
I have a few options, like isPaused and some other things that stops the progressbar filling, cause when user scroll, than it must stop.
But why does it lag? the Interval runs every 1000 (so 1 sec) to fill every 1 sec 10% if isPaused false and the other if things are correct
Your tick function is called every second, thus only every second there is a decision whether to increase the progress bar or not.
I guess the "lags" you discover are just imaginary because your scrolling will never take an exact amount of seconds like 1, 3 or 5 seconds but something like 1.4 or 3.8 seconds. Thus, you think the increase of your progress bar is delayed because it takes some milliseconds until the tick function is called again.
To avoid this effect you could add a listener that fires when no scrolling is performed (in other words, when the scroll stops). In that case you should reset the setInterval function.

How to create a counter that increments by 1 every 1-8 seconds(random)

So I think I'm close, but what I've written begins to increment by larger values, and at an increasing speed the longer it runs. I assume this is an issue with the interval not being properly cleared. Please assist in anyway possible.
<html>
<head>
<script type="text/javascript">
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
clearInterval(interval);
var interval = setInterval(updateCounter, timer);
}
function updateCounter(){
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
setTimer();
}
</script>
</head>
<body style="margin:5%;" onload="setTimer()">
<div id="counter">1</div>
</body>
</html>
Your interval variable is a local variable to setTimer. clearInterval(interval); won't work, because you are passing undefined (the value of interval). It won't throw an error though because of variable hoisting but the value you pass to clearInterval is undefined for sure.
Fix #1:
Declare interval outside setTimer:
var interval;
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
clearInterval(interval);
interval = setInterval(updateCounter, timer); // no redeclaring here
}
Fix #2:
Since you are clearing intervals right before setting them again, you could use setTimeout as it perfectly fit your needs:
function setTimer() {
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
setTimeout(updateCounter, timer); // no clearing is needed this time
}
Note:
Your timer variable will be between 1-6 seconds. You said you wanted it to be 1-8, so use:
var timer = (Math.floor(Math.random() * 8) + 1) * 1000;
I don't think the updateCounter method should know it is called from a timer and be responsible for calling setTimer(). What if you want to call the method to update the counter from somewhere else that is not using a timer. Managing the call to updateCounter should be done by the controlling code IMHO.
Also, using setTimeOut() might be better here as you then don't have to manage the intervals.
function setTimer() {
var timer = (((Math.floor(Math.random() * 6)) + 1) * 1000);
setTimeout(function() {
updateCounter();
setTimer();
}, timer)
}
function updateCounter() {
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
}
<body style="margin:5%;" onload="setTimer()">
<div id="counter">1</div>
</body>
I would suggest moving setTimer() outside of updateCounter() otherwise you will be creating new intervals everytime you call updateCounter(). Try
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
var interval = setInterval(updateCounter, timer);
}
function updateCounter(){
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
}
setTimer();
EDIT: removed clearInterval

Javascript setInterval for sequential numbers

I'm writing some code that looks like this
<script type="text/javascript">
setInterval(function write_numbers(){
var count = 1;
var brk = "<br>"
while (count < 1218){
document.write(count + brk);
count++;
}},1000)
</script>
I need it to display the first number which is one then wait one second then display the next number (2) then wait a second, I need this to carry on till it reaches 1218 then stop.
With the code I've written it just writes all the numbers up, waits a second then repeats all the numbers again.
I'm quite new to coding so i don't know how to fix this.
If someone could tell me how to do it, it would be greatly appreciated.
There are multiple issues in your code, although you are using setInterval(), since you have a while loop inside it, the complete loop will be executed every 1 second.
Instead you need to have the setInterval() callback use an if statement to check whether to print the value or not like
var count = 1;
var interval = setInterval(function write_numbers() {
if (count <= 1218) {
document.body.appendChild(document.createTextNode(count));
document.body.appendChild(document.createElement('br'));
count++;
} else {
clearInterval(interval);
}
}, 1000)
The below script should do the trick for you:
<script>
var count = 1;
var brk = "<br>";
var myVar = setInterval(function(){ myTimer() }, 1000); // This should be a global variable for clearInterval to access it.
function myTimer() {
document.write(count + brk);
count++;
if(count > 1218){
myStopFunction();
}
}
function myStopFunction() {
clearInterval(myVar);
}
</script>
two issues
1) If you are using setInterval then you must clear the interval as well otherwise it will be an infinite loop
2) use if rather than while so that number is printed one by one.
try this
var count = 1;
var interval1= setInterval(function write_numbers(){
var brk = "<br>"
if (count < 1218)
{
document.write(count + brk);
count++;
}
else
{
count = 1;
clearInterval(interval1);
}
},1000);
First, you should define count outside setInterval. Defining inside will reset it every time.
Second, while (count < 1218){} should be a conditional statement. I have considered if(count>= 1218) as termination condition.
Third, when even you use setInterval, remember to use clearInterval as well.
Code
var count = 1;
var interval = setInterval(function write_numbers() {
var brk = "<br>"
document.write(count + brk);
count++;
if (count >= 10) {
window.clearInterval(interval);
}
}, 1000)
Try this code man , only one change from your code.
count variable declare out side of the setInterval function
<script type="text/javascript">
var count = 1;
setInterval(function write_numbers(){
var brk = "<br>"
if (count < 1218)
{
document.write(count + brk);
count++;
}
},1000);
</script>

clearInterval stopping setInterval working purely time based

I'm newbie in JS/jQuery, and got quite confused about the usage of stopping a setInterval function from running in x ms (or after running X times), which apparently happens with clearInterval. I know this question was asked similarly before, but couldn't help me.
As you see, it starts with 1000ms delay, and then repeat for 9000ms (or after running 3 times if better??), and then it needs to stop. What's the most ideal way of doing this? I couldn't properly use the clearInterval function. Thanks for the answers!
var elem = $('.someclass');
setTimeout(function() {
setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
},3000);
},1000);
To stop the interval you need to keep the handle that setInterval returns:
setTimeout(function() {
var cnt = 0;
var handle = setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
if (++cnt == 3) clearInterval(handle);
},3000);
},1000);
Create a counter, and keep a reference to your interval. When the counter hits 3, clear the interval:
var elem = $('.someclass');
setTimeout(function() {
var counter = 0;
var i = setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
counter++;
if (counter == 3)
clearInterval(i);
},3000);
},1000);
Given what you are trying to do is quite static, why not simply add delays and forget all the timers.:
var elem = $('.someclass');
elemt.delay(1000).fadeOut(1500).fadeIn(1500).delay(3000).fadeOut(1500).fadeIn(1500).delay(3000).fadeOut(1500).fadeIn(1500).delay(3000);
Or run the above in a small loop if you want to reduce the code size:
elemt.delay(1000);
for (var i = 0; i < 3; i++){
elemt.fadeOut(1500).fadeIn(1500).delay(3000);
}
You just need to clear the interval after three times:
setTimeout(function() {
var times = 0;
var interval = setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
if (++times > 3) clearInterval(interval);
},3000);
},1000);

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