Use Variable as Time in setInterval / setTimeout [duplicate] - javascript

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 9 years ago.
Here is an example situation.
var count,
time = 1000;
setInterval(function(){
count += 1;
}, time);
The code above will add 1 to the "count" var, very 1000 milliseconds.
It seems that setInterval, when triggered, will use the time it sees on execution.
If that value is later updated it will not take this into account and will continue to fire with the initial time that was set.
How can I dynamically change the time for this Method?

Use setTimeout instead with a callback and a variable instead of number.
function timeout() {
setTimeout(function () {
count += 1;
console.log(count);
timeout();
}, time);
};
timeout();
Demo here
Shorter version would be:
function periodicall() {
count++;
setTimeout(periodicall, time);
};
periodicall();

Try:
var count,
time = 1000,
intId;
function invoke(){
intId = setInterval(function(){
count += 1;
if(...) // now i need to change my time
{
time = 2000; //some new value
intId = window.clearInterval(intId);
invoke();
}
}, time);
}
invoke();
You cannot change the interval dynamically because it is set once and then you dont rerun the setInterval code again. So what you can do it to clear the interval and again set it to run. You can also use setTimeout with similar logic, but using setTimeout you need to register a timeout everytime and you don't need to possibly use clearTimeout unless you want to abort in between. If you are changing time everytime then setTimeout makes more sense.
var count,
time = 1000;
function invoke() {
count += 1;
time += 1000; //some new value
console.log('displ');
window.setTimeout(invoke, time);
}
window.setTimeout(invoke, time);

You cant (as far as i know) change the interval dynamically. I would suggesst to do this with callbacks:
var _time = 1000,
_out,
_count = 0,
yourfunc = function() {
count++;
if (count > 10) {
// stop
clearTimeout(_out); // optional
}
else {
// your code
_time = 1000 + count; // for instance
_out = setTimeout(function() {
yourfunc();
}, _time);
}
};

integers are not passed by reference in JavaScript meaning there is no way to change the interval by changing your variable.
Simply cancel the setInterval and restart it again with the new time.
Example can be found here:
http://jsfiddle.net/Elak/yUxmw/2/
var Interval;
(function () {
var createInterval = function (callback, time) {
return setInterval(callback, time);
}
Interval = function (callback, time) {
this.callback = callback;
this.interval = createInterval(callback, time);
};
Interval.prototype.updateTimer = function (time) {
clearInterval(this.interval);
createInterval(this.callback, time);
};
})();
$(document).ready(function () {
var inter = new Interval(function () {
$("#out").append("<li>" + new Date().toString() + "</li>");
}, 1000);
setTimeout(function () {
inter.updateTimer(500);
}, 2000);
});

Related

How do I loop this function?

I am using Odometer to show an animated counter:
setTimeout(function (){
$('.odometer').html(8567);
}, 1000);
</script>
<script>
window.odometerOptions = {
duration: 3000
};
I would like the counter to start over at the value I've defined in my html (which is 1000) and then count back up to 8567 and repeat indefinitely. I've tried:
$(document).ready(function () {
function loop(){
setTimeout(function (){
$('.odometer').html(8567);},1000,loop);
loop();
});
But it breaks the counter. I'm assuming I can't mix the setTimeout while defining the loop, but don't know what else to try. The 1000 in the setTimeout function is just a coincidence and is the delay to start the function after page load.
If you want to repeatedly call a function over time like this you should use setInterval not setTimeout.
You need to keep track of the current value of the loop, yours right now is setting the counter to 8567 every time.
const start = 1000;
const max = 1010;
var c = start;
var el = document.getElementById('counter');
function counter() {
if (c > max) {
c = start;
}
el.innerHTML = c + "";
c++;
}
counter(); // Optional, can exclude if you want to delay starting the timer
setInterval(counter , 1000)
<div id="counter"></div>

Add delay between 'for' loop iterations

I'm trying to implement basic 60 sec counter(A p element with idcounter), that is triggered after a button(counter_start()) is pressed.But I want delay of 1 sec between this and make sure this updates in browser window in real-time
<script type="text/javascript">
function counter_start(){
x=0
for(i=0;i<60;i++){
x++;
document.getElementById("counter").innerHTML=x;
}
}
</script>
P.S: There might be other simple methods of implementing a timer.But it's not about timer...actually I'm a student and trying to figure out the architecture and mechanism of this.
EDIT: please post tested versions of the code, as some of em' posted below DO NOT update in real time
Try this Example
Hope it will work for u
JS
for(i = 1; i <= 3; i++)
{
(function(i){
setTimeout(function(){
alert(i);
}, 1000 * i);
}(i));
}
Javascript operates synchronously in the browser.
You need to use setTimeout or setInterval to schedule the for loop's body to be called every second. I'm using setTimeout in the below example for easier "garbage collection"; we will never reschedule the tick to happen after we don't need to update things anymore.
<script type="text/javascript">
var counter = 0;
function counter_tick() {
if(counter < 60) {
counter++;
document.getElementById("counter").innerHTML = counter;
setTimeout(counter_tick, 1000); // Schedule next tick.
}
}
function counter_start() {
counter_tick(); // First update, also schedules next tick to happen.
}
</script>
It sounds like you are looking for a way to pause the current thread, which isn't possible in JavaScript and would probably be a bad idea anyway (the user's browser would lock up while the thread was paused).
A timer is really the way to go with this, otherwise you are fighting the way the language is intended to work.
There is no sleep-function in JS. But you can use window.setTimeout to call a function in given intervals:
function counter_start(){
// get current value
var value = document.getElementById("counter").innerHTML*1;
// leave function if 60 is reached
if(value == 60) {
return;
}
// set the innerHTML to the last value + 1
document.getElementById("counter").innerHTML=value+1;
// call next iteration
window.setTimeout(function(){counter_start()}, 100);
}
counter_start();
JSFiddle-Demo
For-loops run to completion, so you wouldn't usually use one for this.
You just need a timer and a variable to increment:
var maketimer = function(){
var tick = 0,
interval_ms = 1000,
limit = 10,
id;
return {
start: function(){
var timer = this;
console.log('start');
id = setInterval(function(){
if(tick === limit){
timer.stop();
timer.reset();
return;
}
tick += 1;
console.log(tick);
}, interval_ms);
},
stop: function(){
console.log('stop');
clearInterval(id);
},
reset: function(){
console.log('reset');
tick = 0;
}
};
};
var t = maketimer();
t.start();
If you really need to use a for-loop, then you could use a generator function. They're part of the proposed ES6 spec., and you'll need Firefox 26+ to try this out. However the only point of doing this would be to learn about generator functions.
var maketimer = function(){
var interval_ms = 1000,
limit = 10,
id,
loop,
it;
loop = function*(){
var i;
for(i=1; i<=limit; i+=1){
yield i;
}
};
it = loop();
return {
start: function(){
var timer = this;
console.log('start');
id = setInterval(function(){
var tick = it.next();
console.log(tick.value);
if(tick.done){
timer.stop();
timer.reset();
return;
}
}, interval_ms);
},
stop: function(){
console.log('stop');
clearInterval(id);
},
reset: function(){
console.log('reset');
it = loop();
}
};
};
var t = maketimer();
t.start();
Try this::
var x=0;
var myVar;
function myTimer() {
x++;
document.getElementById("counter").innerHTML = x;
if(x==60)
clearInterval(myVar);
}
function counter_start(){
myVar=setInterval(function(){myTimer()},1000);
}

How can I pause the javascript function [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 8 years ago.
this is my script to change text every second until it reaches the second eleven. How can I make a function that I can pause?
For example to stop at second five.
<script>
(function () {
var nativeSetTimeout = window.setTimeout;
window.bindTimeout = function (listener, interval) {
function setTimeout(code, delay) {
var elapsed = 0,
h;
h = window.setInterval(function () {
elapsed += interval;
if (elapsed < delay) {
listener(delay - elapsed);
} else {
window.clearInterval(h);
}
}, interval);
return nativeSetTimeout(code, delay);
}
window.setTimeout = setTimeout;
setTimeout._native = nativeSetTimeout;
};
}());
window.bindTimeout(function (t) {
$('.arc').html('<canvas id="mycanvas" width="80" height="80"></canvas>');
$('#vot_ch_s').html((t/1000) + "s");}, 1000);
window.setTimeout(function () {$('.arc').html('<canvas id="mycanvas" width="80" height="80"></canvas>');}, 11000);
</script>
Instead of trying to pause execution and cause the browser to be stuck in some CPU-intensive loop as some might suggest, the optimal way would be to make use of timers. Below is an example using setInterval:
var counter = 0, counter_tick, counter_interval;
var timerTick = function() {
var now = Date.now();
counter += now - counter_tick;
counter_tick = now;
/* do your work here */
$('#counter').html(counter/1000);
};
var startTimer = function() {
counter_tick = Date.now();
counter_interval = setInterval(timerTick, 100);
}
var stopTimer = function() {
clearInterval(counter_interval);
timerTick();
}
$('#start').on('click', startTimer);
$('#stop').on('click', stopTimer);
When the timer starts, and on each tick, it sets counter_tick to the current time in milliseconds. Each tick of the timer, and when the timer is stopped, it calculates how much time has passed since the last tick and adds that to your counter. To "pause" your timer you simply clear it. An example of this can be found here: http://codepen.io/anon/pen/jactn

jQuery - End setInterval Loop

I'm running the following.
setInterval(function()
{
update(url, baseName(data));
}
, 1000);
This calls that update function every second.
Is there a way to keep this functionality of calling update every second, but killing it or ending it after 10 seconds?
Have a counter and store the interval reference, then use clearInterval() to end the calls
var counter = 0;
var timer = setInterval(function () {
counter++;
update(url, baseName(data));
if(counter>=10){
clearInterval(timer)
}
}, 1000);
Keep a counter:
var timesCalled = 0;
var t = setInterval(function() {
update(url, baseName(data));
timesCalled++;
if (timesCalled === 10)
clearInterval(t);
}, 1000);
(clearInterval)

Want a javascript function to run every minute, but max 3 times

I have a ajax javascript method that pulls data from a page etc.
I want this process to run on a timed interval, say every minute.
But I don't want it to loop forever, so max out at 3 times.
What is the best way to implement this?
Like this:
var runCount = 0;
function timerMethod() {
runCount++;
if(runCount > 3) clearInterval(timerId);
//...
}
var timerId = setInterval(timerMethod, 60000); //60,000 milliseconds
A closure-based solution, using setInterval() and clearInterval():
// define a generic repeater
var repeater = function(func, times, interval) {
var ID = window.setInterval( function(times) {
return function() {
if (--times <= 0) window.clearInterval(ID);
func();
}
}(times), interval);
};
// call the repeater with a function as the argument
repeater(function() {
alert("stuff happens!");
}, 3, 60000);
EDIT: Another way of expressing the same, using setTimeout() instead:
var repeater = function(func, times, interval) {
window.setTimeout( function(times) {
return function() {
if (--times > 0) window.setTimeout(arguments.callee, interval);
func();
}
}(times), interval);
};
repeater(function() {
alert("stuff happens!");
}, 3, 2000);
Maybe the latter is a bit easier to understand.
In the setTimeout() version you can ensure that the next iteration happens only after the previous one has finished running. You'd simply move the func() line above the setTimeout() line.
A reusable approach
function setMaxExeuctionInterval( callback, delay, maxExecutions )
{
var intervalCallback = function()
{
var self = intervalCallback;
if ( 'undefined' == typeof self.executedIntervals )
{
self.executedIntervals = 1;
}
if ( self.executedIntervals == maxExecutions )
{
clearInterval( self.interval )
}
self.executedIntervals += 1;
callback();
};
intervalCallback.interval = setInterval( intervalCallback, delay );
}
// console.log requires Firebug
setMaxExeuctionInterval( function(){ console.log( 'hi' );}, 700, 3 );
setMaxExeuctionInterval( function(){ console.log( 'bye' );}, 200, 8 );
This anonymous function (it doesn't introduce any new globals) will do what you need. All you have to do is replace yourFunction with your function.
(function(fn, interval, maxIterations) {
var iterations = 0,
id = setInterval(function() {
if (++iterations > maxIterations)
return clearInterval(id);
fn();
}, interval);
})(yourFunction, 60000, 3);
you can do with setInterval
var count = 0;
var interval = setInterval(yourFunction(), 1000);
function yourFunction (){
clearInterval(interval);
if(count < 3){
count ++;
interval = setInterval(yourFunction(), 1000);
}
// your code
}
To extend Tomalak function:
If you want to know how many cycles are left:
var repeater = function(func, times, interval) {
window.setTimeout( function(times) {
return function() {
if (--times > 0) window.setTimeout(arguments.callee, interval);
func(times);
}
}(times), interval);
}
and use:
repeater(function(left){
//... (do you stuff here) ...
if(left == 0) {
alert("I'm done");
}
}, 3, 60000);
Use setInterval, be sure to get a reference.
var X=setInterval(....);
Also, have a global counter
var c=0;
Inside the function called by the setIntervale do:
c++;
if(c>3) window.clearInterval(X);
You can use setInterval() and then inside the called function keep a count of how many times you've run the function and then clearInterval().
Or you can use setTimeout() and then inside the called function call setTimeout() again until you've done it 3 times.
var testTimeInt = 3;
function testTime(){
testTimeInt--;
if(testTimeInt>0)
setTimeOut("testTime()", 1000);
}
setTimeOut("testTime()", 1000);

Categories