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
Related
Why RangeError: Maximum call stack size exceeded in this.startTime();
startTime() {
$('.m-codeModal-resendTimer').html(this.sectmr);
this.sectmr--;
if (this.sectmr < 0) {
this.sectmr = 0;
$('.m-codeModal-resendErrorNow').fadeIn(0);
$('.m-codeModal-resendErrorSec').fadeOut(0);
$('.m-codeModal-sorry').fadeOut(0);
}
setTimeout(this.startTime(), 1000);
}
Several things...
Add a function keyword to define your startTime function.
Remove the this keyword in the setTimeout reference to startTime.
The function setTimeout takes a callback as a parameter. You, instead of passing a callback parameter to the function, are actually calling the startTime function before the setTimeout function ever has a chance to evaluate and count down 1000 milliseconds.
Here's a simplified example:
var count = 0;
function startTime() {
count++;
document.getElementById('count').innerHTML = count;
setTimeout(startTime, 1000);
}
startTime();
<div id="count"></div>
You're in an infinite loop.
by calling startTime() function call for the first time, you are recursively calling startTime again once you enter the setTimeout function.
In your startTime() function as it is now, there is no way to exit it once you enter.
Maybe you'd want to try
if (this.sectmr < 0) {
...
return;
}
by adding the return statement, once your sectmr goes below zero and enters the if loop, you should be kicked out of the function. I'm not sure what your end goal is, however. Please be a bit more descriptive in the opening question.
The problem is that you're doing setTimeout(this.startTime(), 1000);, executing this.startTime() and using its return value (undefined in this case) as the timer handler. Just remove the ().
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
Look at the following code:
var timer=setTimeout(function(){increase();}, 8);
This setTimeout function will be executed immediately, but I want
it to execute later. Why?
Example:
function increase(i)
{
i++; if(i==100) return;
var timer=setTimeout(function(){increase(i);}, 8);
}
Now, I need to stop and exit this function within another function when certain thing happen:
if (a==b) clearTimeout(timer);
The thing that bothers me is that variable timer is getting assigned, whenever
function increase runs, but it does not need to, and I believe it is bad practice. That is why I need to assign to it only once, before function run and execute it later when need arrives.
I hope you understood, and btw, those are just examples, not my code.
You can declare a variable outside of function the calls setTimeout, define the variable as setTimeout when the function is called; call clearTimeout() from another function with variable referencing setTimeout as parameter.
var timer = null, // declare `timer` variable
n = 0, // reference for `i` inside of `increase`
i = 0,
a = 50,
b = 50,
// pass `increase` to `t`, call `increase` at `setTimeout`
t = function(fn, i) {
// define timer
timer = setTimeout(function() {
fn(i)
}, 8)
};
function increase(i) {
console.log(i);
// set `n` to current value of `i` to access `i`:`n`
// to access `i` value outside of `t`, `increase` functions
n = i++;
if (i == 100) return;
t(increase, i); // call `t`
}
increase(i);
// do stuff outside of `t`, `increase`
setTimeout(function() {
// clear `timer` after `200ms` if `a == b`
if (a == b) {clearTimeout(timer)};
alert(n)
}, 200)
If you want the operation of one function to change the conditions of another, just declare a boolean variable within the scope of both functions and change it's value depending on a terminator function.
For example, take a look at this code:
var exit = false;
function increase(i) {
if(i==100 || exit) return;
setTimeout(function(){ increase(++i) }, 1000);
}
function terminator(a, b){
exit = (a==b);
}
increase(0);
Here, if terminator is ever called with a pair of equal arguments like:
setTimeout(function(){ terminator(true, 1) }, 5000) // timeout of 5 seconds means increase will run 5 times
the recursive call of setTimeout within the increase function will not be reached (after 5 seconds), as the function will return before reaching that line of code.
If terminator is never called, or called with unequal arguments like:
setTimeout(function(){ terminator(true, false) }, 5000) // using setTimeout here is just arbitrary, for consistency's sake
increase will only time out once it's completed 100 recursions (in other words, after 100 seconds have elapsed)
Hope this helps!
Because the delay in setTimeout takes millisecond as time unit, so in your code, you set your function to be executed after 8ms, which feels like immediately.
function increase(i, boolean) {
i++;
if (i == 100) return;
if (boolean) {
var timer = setTimeout(function() {
increase(i, true);
console.log(i);
}, 8);
}
}
increase(1,true);
What about you put in some extra argument
to the function?
While working on my personal project, I've encountered a problem. The problem is every time my function loops the counter counts twice.
JavaScript Code:
function punch(){
var hit;
var h1=100;
h1-=1;
counter++;
hit=setInterval('punch()',2000);
}
What I wanted it to do is that every 2000 milliseconds the counter goes up 1.
In your original code every time the function punch is called is called again internally.
var counter = 0;
function punch(){
var h1=100;
h1-=1;
counter++;
}
var hit = setInterval(punch,2000);
window.setInterval(function(){
/// call your function here
}, 2000);
Call your function where commented and inside the function increment your counter.
var counter = 0;
var h1=100;
setInterval(punch,2000);
function punch(){
h1-=1;
counter++;
}
Here you go: http://jsfiddle.net/9JLdU/3/
<div id="counter"></div>
<script>
var hit;
var counter = 0;
window.punch = function()
{
var h1=100;
h1-=1;
counter++;
document.getElementById('counter').innerHTML=counter;
}
hit = setInterval('punch()',2000);
</script>
setInterval will cause the function to be called about every 2 seconds until cancelled. By including another call to setInterval within the function, another sequence of calls is established each time it is called, so eventually you'll have thousands of instances running, each incrementing the counter.
So either use one call to setInterval, or have the function call itself using setTimeout, which only runs once. Also, it's preferred to pass a function reference to setInterval and setTimeout as passing a string calls the Function constructor and is effectively a call to eval, which is needlessly expensive in terms of system resources.
var counter = 0;
function punch() {
// ...
counter++;
hit = setTimeout(punch, 2000);
}
punch();
or
var counter = 0;
function punch() {
// ...
counter++;
}
setInterval(punch, 2000);
The advantage of setTimeout is that you can easily vary the delay based on some other logic, or stop the sequence without cancelling the timeout.
Note that when doing:
hit = setInterval(...);
the value of hit is an index that can be used to cancel the interval, it is not the value returned by punch (which is undefined since there is no return statement).
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
Read about setInerval() Here
Syntax
setInterval(function,milliseconds)
Working Example here
<script>
var hit = 100;
counter = 0;
var myVar = setInterval(function() {punch()}, 1000);
function punch() {
hit--;
counter++;
}
</script>
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>