JavaScript: how to control progress speed? - javascript

Is there any option to increase and decrease the speed of the progress?
Sometimes progress takes time and sometime very slow to finish:
var value = 0,
interval = setInterval(function() {
value = ((+value) + .1).toFixed(1);
if(value == 80.5) clearInterval(interval);
$('p').html(value+'%');
},2);
http://jsfiddle.net/sweetmaanu/zjdBh/13/

You'll note that your code is using setInterval(). This global JavaScript function is used for periodically executing code at a given time interval. It takes two arguments for its typical usage (which is the way you are using it here). It returns a unique ID that can be used to identify your particular interval function (since multiple ones can be set up simultaneously).
The first argument is a function to be executed on the interval. Your function is the anonymous function:
function() {
value = ((+value) + .1).toFixed(1);
if (value == 80.5) clearInterval(interval);
$('p').html(value + '%');
}
This function will increase the percentage progress on each execution.
The second argument is an integer number for the number of milliseconds (thousandths of a second) to let elapse before the function from the first argument is executed. This is the key part for your question, I believe. Your code has 2 (on the last line of your posted code), so it will wait 2 milliseconds before executing your function (which increments the percentage progress), and then it will wait 2 more milliseconds, then execute the same function again, etc.
By simply changing the value of the second argument, you can change how fast or slow your function executes each time, which changes how fast or slow your percentage increases. So if you set it to 500, then setInterval will wait for a half a second before each execution of the function.
You can read about the other JavaScript timer functions here, in particular about clearInterval(), which your code uses in the anonymous function to end the interval when you reach 80.5%.

I hope this helps:
$(function(){
var value1 = 0;
var value2 = 0;
var span1 = $('#val1');
var span2 = $('#val2');
var interval1 = setInterval(function(){
span1.text(++value1);
if (value1 === 80) {
clearInterval(interval1);
clearInterval(interval2);
interval1 = null;
interval2 = null;
span2.text(5);
}
}, 100); // you can change speed here
var interval2 = setInterval(function() {
span2.text(value2++ % 10);
}, 70);
});
HTML:
<body>
<div class="progress-bar"></div>
<hr>
<p><span id="val1">0</span>.<span id="val2">1</span>%</p>
</body>

Related

setTimeout not waiting specified time

My setTimeout statements are making function calls instantly instead of waiting the time I specified and I'm not sure why. It should take 10 seconds for the for loop and then 110 seconds to change a boolean value from T to F.
for(var c = 0; c < 10; c++)
{
setTimeout(function()
{
gold = gold + clickerPower;
$("#totalGold").html("Gold: " + gold);
console.log("Clicked!");
}, 1000);
}
setTimeout(function(){frenzyActive = false;}, 110000);
Starting a timeout is an asynchronous operation. setTimeout accepts a function as it's first argument because it's registering that callback function to be invoked at a later time. Every iteration of the JavaScript event loop it checks to see if the appropriate time has passed and if so then it fires the registered callback. Meanwhile it's still moving on to run other code while it waits.
Your for loop is not waiting for anything. It iterates to 10 super fast and all you've done is register ten callbacks to fire all at the same time in exactly one second (the time is specified in milliseconds by the way, so 1000 = 1 second).
You need setInterval.
var count = 0;
var intervalId = setInterval(function () {
gold = gold + clickerPower;
$('#totalGold').html('Gold: ' + gold);
console.log('Clicked!');
count++;
if (count === 10) {
clearInterval(intervalId);
frenzyActive = false;
}
}, 1000);
That function will run once every second and increment a count variable each time. When it reaches 10 we call clearInterval and give it the intervalId returned from setInterval. This will stop the interval from continuing.
Take a gander at this post I wrote back when I too was confused about asynchronous callbacks :)
http://codetunnel.io/what-are-callbacks-and-promises/
I hope that helps :)
Good luck!
It will not take 10 seconds to execute the loop. Look will execute immediately and the anonymous function will be enqueued 10 times to be executed after 1 second.
The last call to setTimeout will cause the anonymous function to be executed after 110 seconds.
To ensure that the anonymous function within the loop is called sequentially, 10 times, after a gap of 1 second each, do the following:
var c = 0;
setTimeout(function() {
if(c < 10) {
gold = gold + clickPower;
console.log("Clicked");
c++;
setTimeout(arguments.callee, 1000);
//^^ Schedule yourself to be called after 1 second
}
}, 1000);
I did come across this challenge today, and the answer provided by #Guarav Vaish set me on a path to success. In my case, I am using ES6 syntax and its worth noting that the arguments.callee is deprecated. However, here is how I'd write the same solution as contributed by Vaish:
var c = 0;
setTimeout(function named() {
if(c < 10) {
gold = gold + clickPower;
console.log("Clicked");
c++;
setTimeout( ()=>{ named() }, 1000);
//^^ Schedule yourself to be called after 1 second
}
}, 1000);
Note: I am simply using a named function in place of the anonymous one in the original solution. Thank you. This was really helpful

javascript timer counting very fast as time passes

I want a counter which reset in specific interval of time. I wrote this code. When I refresh the page it is executing perfectly. But as time passes the timer goes really fast, skipping seconds. Any idea why this is happening.
function countdown_new() {
window.setInterval(function () {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter) - eval(1);
$("b[id=show-time]").html(updateTime);
if (updateTime == 0) {
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(countdown_new());
// countdown_new();
//my_ajax();
}
}, 1000);
}
window.setInterval(function () {
countdown_new();
}, 5000)
HTML
Coundown in 5 seconds
The issue is because you are not clearing the previous timer before starting a new one, so you start a new one for each iteration. To clear the timer you should save a reference to it, and pass that to clearInterval, not a function reference.
Also, note that your pattern of using multiple intervals for different operations can lead to overlap (where two intervals are acting at the same time and cause odd behaviour). Instead, use setTimeout for the initial 5 second delay and then chain further calls to stop this overlap.
Try this:
var timer;
function countdown_new() {
timer = setInterval(function () {
var $showTime = $("#show-time")
var updateTime = parseInt($showTime.text(), 10) - 1;
$showTime.html(updateTime);
if (updateTime == 0) {
$showTime.html('5');
clearInterval(timer);
setTimeout(countdown_new, 5000);
}
}, 1000);
}
setTimeout(countdown_new, 5000);
Example fiddle
Note that you should use the # selector to select an element by its id attribute, and you should never use eval - especially not for type coercion. To convert a value to an integer use parseInt().
You are calling window.setInterval(), which schedules a function call to countdown_new() ever 5 seconds without stop.
Compounding the problem, you are calling countdown_new() again inside your clear interval.
You need to call setInterval just once to continuously execute a function every 5 seconds.
If you want to cancel an interval timer, you need do to this:
var intervalObj = setInterval(function() { ... }, 5000);
clearInterval(intervalObj);
Yes clearinterval does the trick.
function countdown_new(){
t = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(t);
// countdown_new();
my_ajax();
}
}, 1000);
}

what is the execution mechanism of the setInterval function

I want to know, How it works the setInterval function.
First: I have simple example (Live demo)
Also the code below.
HTML:
<div id="elem"></div>
<div id="count"></div>
<div id="Timer"></div>
Javascript:
var s = 10;
var count = 0;
if (s == 20) alert("S= 20");
var timer = setInterval(function () {
if (count < 50) {
count++;
document.getElementById('count').innerHTML = "Counter: " + count;
}
else {
clearInterval(timer);
document.getElementById('count').innerHTML = "Counter: End Of Count";
}
}, 50);
s = 20;
document.getElementById('elem').innerHTML = "variable 's': " + s;
document.getElementById('Timer').innerHTML = "Timer value: " + timer;
if (s == 20) alert("S= 20");
All I want is how the function it works.
After implement the code of function , is it return to the beginning of code at top page , or return to implement the function code again until use clearInterval function.
Anybody help me please.
In your code, you are supplying an anonymous function to setTimeout.
The anonymous function supplied to setInterval is called asynchronously. The anonymous function cannot run for the first time until the current function is complete. The call to setInterval(function() {...}) is registering your anonymous function for execution every 50ms; it does not execute immediately.
Your program flow runs like this:
set initial variables
check if s == 20
register (not execute) the anonymous function with setInterval
set s = 20
print results
check if s == 20
end of your code blcok
...
50ms later, the first call to your anonymous setTimeout function finally happens
Repeatedly call the anonymous function every 50ms
Takeaway point: If you need certain operations to happen after the anonymous function completes, put those operations inside the anonymous function itself. In your code, I suspect you want some lines that currently come after the setTimeout call and place them inside the else block in your anonymous function.
setInterval keeps calling the enclosed function repeatedly till clearinterval is called. the delay can be given in seconds 1000 = 1 sec, since you have given a small delay of 50 the function is called repeatedly in quick succession till it reaches the 50 limit

Increase the value of a number in an element every x milliseconds

So I have this simple HTML:
<span id="badge">0</span>
I want the number 0 to increase by 1 every x milliseconds. How do I do that with Javascript (with or without jQuery)?
Thanks a bunch - I'm new to this :)
You should do this:
<script>
var $badge = $('#badge'); // cache
setInterval(function () {
var value = parseInt($badge.html());
value++;
$badge.html(value);
}, 1000);
</script>
Assuming 1000 milliseconds.
function increment() {
document.getElementById("badge").value = Number(document.getElementById("badge").value) + 1;
setTimeout("increment()",3000);
}
increment()
Every of the answers I see here has the same drawbacks:
performance issue because of selecting the DOM element every ms cycle. Especially when using a heavy library as jQuery.
setInterval() is probably the tool designed for that functionality, but not reliable. It can diverge a lot from the real time, especially when using a small interval. If you want exactly x executions per second, you may google for some timing libraries.
I would code:
var textNode = document.getElementById(badge).firstChild;
var start = Date.now();
window.setInterval(function update() {
textNode.data = Math.round((new Date()-start)/ms);
}, ms);
If you don't want to start at 0, it will be trivial to add an offset (determined before the loop begins), eg.
var start = Date.now() - (textNode.data * ms || 0); // NaN catching, implicit number cast
Something like this?
var millisecs = 10;
setInterval(function() {
var $badge = $('#badge');
$badge.text(parseInt($badge.text())++);
}, millisecs);
http://jsfiddle.net/iambriansreed/MPP8n/3/
Check this http://www.w3schools.com/js/js_timing.asp
A little more about timers:
// setting a variable for your timer will allow you the ability to "turn it on and off"
var tmrChangeI;
// setTimeout is a function to initiate a function once after given amount of milisecs
// whereas setInterval will continue a function until cancled every so many milisecs
// the following wil "turn on" your timer
tmrChangeI = setInterval(function() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
}, 500); // 500 will = every half of a second
// to "turn off" timer
clearInterval(tmrChangeI);
// or set a bool to test and use timeout to repeat till bool is false
var tmrBool = true;
// establish function to execute
function tmrFunc() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
if (tmrBool) tmrChangeI = setTimeout(function() { tmrFunc(); }, 500); // 500 will = every half of a second
};
// execute function, begin timer
tmrChangeI = setTimeout(function() { tmrFunc(); }, 500);
// clear via bool allowing one more execution
tmrBool = false;
// clear by force possibly stoping next execution,
// tho in this manner it may be too late if timer is very short
// and maybe overriden by bool still being true, this is not safest
// but is example of how to use setTimeout
clearTimeout(tmrChangeI);
You can use setInterval.
var $badge = $('#badge');
setInterval(function () {
$badge.html(parseInt($badge.html()) + 1);
}, 1);​//Specify the milliseconds here, right it will update the value every 1 millisecond
Working demo - http://jsfiddle.net/8FMZh/
You could create a Jquery plugin, so you can reuse whenever you need.
$.fn.increment= function(options) {
var $this = $(this);
var coef = options.coef;
var speed = options.speed;
var value = 0;
setInterval(function(){
value = value + coef ;
$this.html(value);
}, speed);
};
And in your main javascript file :
$("#badge").increment({coef: 1, speed:1000});
working demo : http://jsfiddle.net/8FMZh/102/

JavaScript. a loop with innerHTML is not updating during loop execution

I'm trying to refresh a div from Javascript at each loop and see 1, 2, 3, ....
The following code works, but only displays the final result (9998).
How is it possible to display all the steps?
Thank you in advance.
<html>
<head>
</head>
<body>
<div id="cadre" style="width=100%;height=100%;">
<input type="button" value="Executer" onclick="launch();"/>
<div id="result" ></div>
</div>
<script type="text/javascript">
function launch(){
for (inc=0;inc<9999;inc++){
document.getElementById('result').innerHTML = inc;
}
}
</script>
</body>
</html>
JavaScript execution and page rendering are done in the same execution thread, which means that while your code is executing the browser will not be redrawing the page. (Though even if it was redrawing the page with each iteration of the for loop it would all be so fast that you wouldn't really have time to see the individual numbers.)
What you want to do instead is use the setTimeout() or setInterval() functions (both methods of the window object). The first allows you to specify a function that will be executed once after a set number of milliseconds; the second allows you to specify a function that will be executed repeatedly at the interval specified. Using these, there will be "spaces" in between your code execution in which the browser will get a chance to redraw the page.
So, try this:
function launch() {
var inc = 0,
max = 9999;
delay = 100; // 100 milliseconds
function timeoutLoop() {
document.getElementById('result').innerHTML = inc;
if (++inc < max)
setTimeout(timeoutLoop, delay);
}
setTimeout(timeoutLoop, delay);
}
Notice that the function timeoutLoop() kind of calls itself via setTimeout() - this is a very common technique.
Both setTimeout() and setInterval() return an ID that is essentially a reference to the timer that has been set which you can use with clearTimeout() and clearInterval() to cancel any queued execution that hasn't happened yet, so another way to implement your function is as follows:
function launch() {
var inc = 0,
max = 9999;
delay = 100; // 100 milliseconds
var iID = setInterval(function() {
document.getElementById('result').innerHTML = inc;
if (++inc >= max)
clearInterval(iID);
},
delay);
}
Obviously you can vary the delay as required. And note that in both cases the inc variable needs to be defined outside the function being executed by the timer, but thanks to the magic of closures we can define that within launch(): we don't need global variables.
var i = 0;
function launch(){
var timer = window.setInterval(function(){
if( i == 9999 ){
window.clearInterval( timer );
}
document.getElementById('result').innerHTML = i++;
}, 100);
}
launch();
Try
document.getElementById('result').innerHTML += inc;

Categories