How to stop a setTimeout for a decided time - javascript

var time = 1000;
var point = 0;
function interval() { timeout = setTimeout(increment, time);}
function increment(){point += 1;document.getElementById("pul").value = point;interval();}
time2 = 3000;
function fermafatica() {setInterval(ferma, time2);}
function ferma(){clearTimeout(timeout)}
i need to stop the interval() function or the setTimeout in interval() for only 1000ms and then to keep it working

Are you asking about how to clear a timeout after X seconds? I would consider just having a static variable (lets just call it X) count up within the repeating function, and if the function repeats every 10ms, and you want it to run for 1000ms, then when x==100, clear the timeout.

You could try:
setTimeout(function() {
z();
// Do anything else here
}, 1000);
The setTimeout function, runs the given function after a set amount of time. This will call the z() function, which clears your timeout, after the supplied time of 1000ms.
EDIT: Everything: See below
var time = 1000;
var point = 0;
function interval() { timeout = setTimeout(increment, time);}
function increment(){point += 1;document.getElementById("pul").value = point;interval();}
time2 = 3000;
function fermafatica() {setInterval(ferma, time2);}
function ferma(){clearTimeout(timeout)}
Change function fermafatica() {setInterval(ferma, time);}
to function fermafatica() {setTimeout(ferma, time);}

ok.... i "avoid" the problem.... i need to stop the setTimeout for 1000ms and then let it works normally... i tried so... instead of pausing the setTimeout I put another time var.
var time = 1000;
var timecache = 1000;
fatica = 3000;
sudore = 3000;
function interval() { timeout = setTimeout(increment, time);} //here setTimeout uses var time//
function increment(){console.log(time);point += 1;document.getElementById("pul").value = point;interval();}
function fermafatica() {time = timecache;setInterval(ferma, fatica);} //here the function equals time to timecache so vas time is always 1000ms//
function ferma(){time = 10000; setTimeout(fermafatica, sudore);} // then here I transformed the time in 10000 so the first function will take 10000 instead of 1000 in setTimeout//
//plus i put a setTimeout to recall function fermafatica() that reset the time to 1000//
this i what i want... I avoid the problem and found another way to do that... but it works...

Related

How to exec a function after previous ends?

guys. It's a timer. I wanna run the timer and when it's end do something else(like a warning),and then run again with other amount of minutes. But I can't cause always only the second call is executed:
$(document).ready(function() {
timer(5,timer(25));
// timer(5);
// timer(25); do not work... only exec de last one
});
function timer(countTo,callback){
var time = 10; /* how long the timer runs for */
var initialOffset = '440';
var i = 1
var interval = setInterval(function() {
$('.circle_animation').css('stroke-dashoffset', initialOffset-(i*(initialOffset/countTo)));
$('h2').text(i);
if (i == countTo) {
clearInterval(interval);
}
i++;
}, 1000);
callback();
}
Which is the best solution? There is something that I am not understanding... Thanks anyway!
Well, first off:
timer(5,timer(25));
If you think this line will execute timer(5), and then at the end of timer(5) it will execute timer(25), you are mistaken. This is actually going to evaluate timer(25) immediately, and pass its return value (undefined) as the second parameter to timer(5,undefined).
If you intended to pass that as a callback, you need to pass a function. So you could do:
timer(5,timer.bind(null,25));
But, for that matter, you don't even check if callback exists before attempting to invoke it, so you probably are getting a reference error anyway.
timer(5,timer(25));
starts two timers and passes the result of the second (undefined) to the first as callback. You want:
timer(5,timer.bind(window,25));
And the callback needs to be executed if i==countTo ...
Is this what you want?
timer(5,function(){timer(25)});
Your problem is here:
timer(5,timer(25));
You should type
timer(5, function(){
timer(25)
});
//or using ES6 syntax
timer(5, () => timer(25));
because timer(25) returns its value (this function doesn't return value so it tries to invoke undefined), not that function.
Also read about closures, it might be helpful.
Instead of runing a callback(), you need to run the function itself (timer()). You'll also need to run a for loop inside your function that checks how many times the function has already run. If it reaches your desired maximum, break out of that. This way it won't run indefinitely.
In the following example, the timer() function executes five times, which is what I'm assuming you want by calling timer(5).
$(document).ready(function() {
timer(5);
});
function timer(countTo) {
for (var iterations = 0; iterations < countTo; iterations++) {
var time = 10; /* how long the timer runs for */
var initialOffset = '440';
var i = 1
var interval = setInterval(function() {
$('.circle_animation').css('stroke-dashoffset', initialOffset - (i * (initialOffset / countTo)));
$('h2').text(i);
if (i == countTo) {
clearInterval(interval);
}
}, 1000);
timer();
console.log("Iteration:", iterations + 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To run the function 25 times after this, all you have to do is call timer(25) directly after timer(5):
$(document).ready(function() {
timer(5);
timer(25);
});
$(document).ready(function() {
timer(5);
timer(25);
});
function timer(countTo) {
for (var iterations = 0; iterations < countTo; iterations++) {
var time = 10; /* how long the timer runs for */
var initialOffset = '440';
var i = 1
var interval = setInterval(function() {
$('.circle_animation').css('stroke-dashoffset', initialOffset - (i * (initialOffset / countTo)));
$('h2').text(i);
if (i == countTo) {
clearInterval(interval);
}
}, 1000);
timer();
console.log("Iteration:", iterations + 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this helps! :)

Settimeout and ClearTimeout

i need to restart a setTimeout after stopping it with a clearTimeout
the code is like:
function start(){timeout = setTimeout(function(){...}, 1000}
function increment(){interval();}
function stop(){clearTimeout(timeout)}
better explained:
function start() is a timeout of 1000ms for another function that recall start().
function increment() just add +1 to a value every 1000s but it doesn't matter with the problem.
the last function stop() stops the setTimeout in the function start().
i need to stop the setTimeout in start() for just 1000ms and then let it continue working.
ok.... i "avoid" the problem....
i need to stop the setTimeout for 1000ms and then let it works normally...
i tried so... instead of pausing the setTimeout I put another time var.
var time = 1000;
var timecache = 1000;
fatica = 3000;
sudore = 3000;
function interval() { timeout = setTimeout(increment, time);} //here setTimeout uses var time//
function increment(){console.log(time);point += 1;document.getElementById("pul").value = point;interval();}
function fermafatica() {time = timecache;setInterval(ferma, fatica);} //here the function equals time to timecache so vas time is always 1000ms//
function ferma(){time = 10000; setTimeout(fermafatica, sudore);} // then here I transformed the time in 10000 so the first function will take 10000 instead of 1000 in setTimeout//
//plus i put a setTimeout to recall function fermafatica() that reset the time to 1000//
this i what i want... I avoid the problem and found another way to do that... but it works... thank you anyway

How to make Javascript execute a code every x seconds, but make it wait before a function was fully executed?

Here I have a piece of code that auto-executes every 2 seconds. However, the time it takes to execute function roll() varies due to the Internet connection's peaks and bottoms. I'm trying to make the function roll() execute itself automatically every 2 seconds, but the code must wait till the function is fully executed before proceeding and auto-executing again.
P.S. Any suggestions of a better title for this question would be appreciated.
var init = 0.01
var start = init
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")
function roll() {
$bet.val(start)
$button.click()
setTimeout(function() {
var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
var cls = tr.getAttribute('class')
if (cls === 'success'){
start = init
$bet.val(start)}
else{
start = start * 2
$bet.val(start)
$odds.click()}
$button.click();
setTimeout(function() {
$button.click();
},1000);
},1000);
}
setInterval(roll, 2000)
Don't use setInterval. It will try to call a function after the elapsed time regardless whether it's finished or not. setTimeout is better, as you can control when it gets called. And you quite normally just call it at the end of a function (where it calls itself).
E.g.
function draw() {
// Some drawing here...
setTimeout(draw, 50);
}
So, when you call draw() above, it will do its operations, then wait 50 ms and then call itself again, repeatedly.
See here for further details on the difference.
I added setTimeout to the roll function and called it at the end.
var init = 0.01
var start = init
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")
function roll() {
setTimeout(roll, 2000)
$bet.val(start)
$button.click()
setTimeout(function() {
var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
var cls = tr.getAttribute('class')
if (cls === 'success'){
start = init
$bet.val(start)}
else{
start = start * 2
$bet.val(start)
$odds.click()}
$button.click();
setTimeout(function() {
$button.click();
},1000);
},1000);
}
roll()
The best would be to do soemething like this:
function roll() {
var time = Date.now();
//your stuff goes here
setInterval(roll, Math.max(2000 - (Date.now() - time)), 1);
}
This tries to optimize tge amount of time between calls, so if the function took 1.5 seconds, then it will fire after 0.5 seconds.

how do I start and stop a timer from an options page

Right now i have this 1 minute timer in my background page that runs forever i would like to be able to start and stop it from an options page.
chrome.browserAction.setBadgeBackgroundColor({color:[0, 0, 0, 255]});
var i = 1;
window.setInterval(function(timer) {
chrome.browserAction.setBadgeText({text:String(i)});
i++;
}, 60000);
setInterval() method of the Window object schedules a function to be invoked repeatedly at intervals of the specified number of milliseconds. setInterval() returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function. Read more about How Javascript Timers work. With that you can write something like this:
My.Controller = {};
(function() {
var interval = 10;
var timer = null;
function init (param) {
// initialisations if any
}
// Override the default interval of 10 seconds by passing new interval
function startAction (param, tInterval) {
// Set a timer
var ti = (!tInterval) ? interval : tInterval;
timer = setInterval(My.Controller.action, ti * 2000);
}
function action () {
// Logic here
}
function stopAction () { clearInterval(timer); }
var c = My.Controller;
c.init = init;
c.startAction = startAction;
c.stopAction = stopAction;
})(); // end Controller
Now you can say My.Controller.startAction() to start the timer and and My.Controller.stopAction() to stop.
Read and explore about namespaces in JavaScript.
Hope this helps.

Change millisec for window.setInterval function

I used window.setInterval function. this function includes 3 arguments :
setInterval(code,millisec,lang)
I used that like this:
var counter = 1;
window.setInterval(function() {}, 1000 * ++counter);
but when first time set timer (second argument), is not changed and that act Like below code:
window.setInterval(function() {}, 1000);
please write correct code for change timer
Use window.setTimeout instead.
var delay = 1000;
function myTimer() {
// do whatever
window.setTimeout(myTimer, delay);
}
window.setTimeout(myTimer, delay);
You can manipulate delay in the body of your function.
Your problem is that javascript first execute '1000 * ++counter' once and then do not update the time interval.
You should try to use a timeout instead: https://developer.mozilla.org/en/DOM/window.setTimeout
And create a new time out with the new value every time your time out function is called.
Sounds like what you're after is not setInterval but rather setTimeout in a loop:
var counter = 1;
for (var i = 1; i <= 3; i++) {
window.setTimeout(function() {
alert("#" + counter);
counter++;
}, i * 1000);
}
This will execute three different "timers" one after the other.
Live test case: http://jsfiddle.net/86DRd/

Categories

Resources