javascript setTimeout function does not work - javascript

I am trying to update a variable every one second. For that reason I am using setTimeout. But it does not update the variable. It logs out 0 just once. Here is my code
var yes=0;
setTimeout(function () {
console.log(yes);
yes++;
}, 1000);​

Use setInterval, to finish the repitition you have to clear the interval using clearInterval(yourInterval);
Live Demo
var yes=0;
yourInterval = setInterval(function () {
console.log(yes);
yes++;
}, 1000);​

setTimeout does repeat itself only once, try setInterval so that for every second it increments yes with 1
but remember to clear the interval after sometime else you get on to a never ending loop
using clearInterval()

setTimeOut method is just called once after a specific timeout which in your case is 1000, try to use setInterval method instead

jsBin demo with setTimeout
If you really want to stick to setTimeout (I appreciate that ;) )
than just wrap all into a function and recall it inside it self like:
var yes=0;
(function loop(){
setTimeout(function () {
console.log(yes);
yes++;
loop(); // loop recall
}, 1000);
})();
Otherwise go for setInterval:
var yes=0;
function count(){
console.log(yes);
yes++;
}
setInterval(count, 1000);

Related

How would I make this function repeat? [duplicate]

I want repeat this code every 4 seconds, how i can do it with javascript or jquery easly ? Thanks. :)
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup);
$("#prompt").animate({"top": "+=25px"}, 500).delay(2000).animate({"top": "-=25px"}, 500).delay(500).html("");
}
});
Use setInterval function
setInterval( fn , miliseconds )
From MDC docs:
Summary
Calls a function repeatedly, with a fixed time delay between each call to that function.
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
where
intervalID is a unique interval ID you can pass to clearInterval().
func is the function you want to be called repeatedly.
code in the alternate syntax, is a string of code you want to be executed repeatedly. (Using this syntax is not recommended for the same reasons as using eval())
delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.
Example
// alerts "Hey" every second
setInterval(function() { alert("Hey"); }, 1000);
setInterval(function(){
// your code...
}, 4000);
It's not too hard in javascript.
// declare your variable for the setInterval so that you can clear it later
var myInterval;
// set your interval
myInterval = setInterval(whichFunction,4000);
whichFunction{
// function code goes here
}
// this code clears your interval (myInterval)
window.clearInterval(myInterval);
Hope this helps!
Another possibility is to use setTimeout, but place it along with your code in a function that gets called recursively in the callback to the $.get() request.
This will ensure that the requests are a minimum of 4 seconds apart since the next request will not begin until the previous response was received.
// v--------place your code in a function
function get_request() {
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup)
.animate({"top": "+=25px"}, 500)
.delay(2000)
.animate({"top": "-=25px"}, 500)
.delay(500)
.html("");
}
setTimeout( get_request, 4000 ); // <-- when you ge a response, call it
// again after a 4 second delay
});
}
get_request(); // <-- start it off
const milliseconds = 4000
setInterval(
() => {
// self executing repeated code below
}, milliseconds);
Call a Javascript function every 2 second continuously for 20 second.
var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
intervalPromise = $interval(function() {
fn();
var currentTime = new Date().getTime() - $scope.startTime;
if (currentTime > timeoutTime){
$interval.cancel(intervalPromise);
}
}, delay);
};
$scope.startTimer(hello, 2000, 10000);
hello(){
console.log("hello");
}

How to stop time interval in my function?

I have this function:
function timedFunction(functionString,timeoutPeriod) {
setTimeout(functionString+"timedFunction(\""+functionString+"\","+timeoutPeriod+");",timeoutPeriod);}
This function me call:
timedFunction("startStopky();",1000);
startStopky(); is a function that I want in a specified time interval repeatedly run. Everything works excellently, but if I want stop this interval, I have to stop as follows:
for (var i = 1; i < 99999; i++) {
window.clearInterval(i);
}
Unfortunately this will stop all intervals, and I want to stop just one particular. How can I do it?
Instead of doing recursive calls to timedFunction just do:
var intervalId = setInterval(startStopky, 1000);
and to clear it just do:
clearInterval(intervalId);
The setTimeout function returns a timeout ID that you use with clearTimeout to remove that timeout. The same goes for intervals but in that case it's a setInterval and clearInterval combo.
E.g.:
var t = setTimeout(yourFunction, 1000);
clearTimeout(t);
var i = setInterval(yourFunction2, 500);
clearInterval(i);
You have a Timeout, but you are clearing an Interval. clearInterval clears intervals, not timeouts.
You want window.clearTimeout(timeoutId)
If you want to stop a single one, you use the processId of that interval.
window.clearTimeout("13");
You really shouldn't be using strings to do this:
function timedFunction(fn, interval) {
var timerHandle;
function runIt() {
fn();
timerHandle.id = setTimeout(runIt, interval);
}
return timerHandle = { id: setTimeout(runIt, interval) };
}
Then you can call it like this:
var handle = timedFunction(startStopky, 1000);
To stop the process:
clearTimeout(handle.id);

jquery delay between javascript functions

I have multiply functions with parameters simplified as:
function f1(p1,p2){
alert('Function one is P1:'+p1+' P2:'+p2);
}
function f2(p1,p2){
alert('Function two is P1:'+p1+' P2:'+p2);
}
I need to fire these is a sequence with a delay between. I have however found that jQuery dislikes running functions with parameters. I have tried the .click function.
$.delay(1000).click(f1('One',false)).delay(1000).click(f2('One',false));
But the delay makes the click functions not work...
I would just use a simple timeout:
f1("one", false);
setTimeout(function() { f2("one", false); }, 1000);
$.delay(1000).click(function(){f1('One',false);}).delay(1000).click(function(){f2('One',false);});
not sure what the click is for though ...
if you want to delay a function call then a much simpler way is to use setTimeout().
eg:
// calling it in a nested setTimeout for sequential delayed execution
setTimeout(function(){
f1('One',false);
setTimeout(function(){
f1('One',false)
},300)
},300)
function fn1()
{
alert(1);
}
function fn2()
{
alert(2);
}
var arr=[fn1,fn2];
var len=arr.length;
var time=1000;
for(var k=0;k<len;k++)
{
(function(k)
{
setTimeout(arr[k],time);
}(k))
time=time*2;
}
It executes after a delay of 1 second!
DEMO

Using jQuery, how do I repeat a function in different intervals?

I need the function to repeat after 8 seconds the first time and then again after 30 seconds. I have used setTimeout but not sure if this is the way to go about it.
Thank you.
You could use a conjunction of setTimeout and setInterval:
window.setTimeout(function() {
// this will run 8 seconds later
window.setInterval(function() {
// do here whatever you want to do at 30 seconds intervals
}, 30000);
}, 8000);
setTimeout is perfect.
(function() {
var func = function() {
// Code here
}
setTimeout(func, 8000);
setTimeout(func, 30000);
})();
Use javascript:
var interval = setInterval(yourFunction, 8000);
Where 8000 is the interval after which your function is executed again, and interval is a handle to the interval, in case you want to stop it using clearInterval

Repeat code every 4 seconds

I want repeat this code every 4 seconds, how i can do it with javascript or jquery easly ? Thanks. :)
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup);
$("#prompt").animate({"top": "+=25px"}, 500).delay(2000).animate({"top": "-=25px"}, 500).delay(500).html("");
}
});
Use setInterval function
setInterval( fn , miliseconds )
From MDC docs:
Summary
Calls a function repeatedly, with a fixed time delay between each call to that function.
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
where
intervalID is a unique interval ID you can pass to clearInterval().
func is the function you want to be called repeatedly.
code in the alternate syntax, is a string of code you want to be executed repeatedly. (Using this syntax is not recommended for the same reasons as using eval())
delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.
Example
// alerts "Hey" every second
setInterval(function() { alert("Hey"); }, 1000);
setInterval(function(){
// your code...
}, 4000);
It's not too hard in javascript.
// declare your variable for the setInterval so that you can clear it later
var myInterval;
// set your interval
myInterval = setInterval(whichFunction,4000);
whichFunction{
// function code goes here
}
// this code clears your interval (myInterval)
window.clearInterval(myInterval);
Hope this helps!
Another possibility is to use setTimeout, but place it along with your code in a function that gets called recursively in the callback to the $.get() request.
This will ensure that the requests are a minimum of 4 seconds apart since the next request will not begin until the previous response was received.
// v--------place your code in a function
function get_request() {
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup)
.animate({"top": "+=25px"}, 500)
.delay(2000)
.animate({"top": "-=25px"}, 500)
.delay(500)
.html("");
}
setTimeout( get_request, 4000 ); // <-- when you ge a response, call it
// again after a 4 second delay
});
}
get_request(); // <-- start it off
const milliseconds = 4000
setInterval(
() => {
// self executing repeated code below
}, milliseconds);
Call a Javascript function every 2 second continuously for 20 second.
var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
intervalPromise = $interval(function() {
fn();
var currentTime = new Date().getTime() - $scope.startTime;
if (currentTime > timeoutTime){
$interval.cancel(intervalPromise);
}
}, delay);
};
$scope.startTimer(hello, 2000, 10000);
hello(){
console.log("hello");
}

Categories