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

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

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");
}

Looping a script every x seconds

I'm wondering how to loop a script every x seconds. I'm relatively new to javascript and jquery, however I do know how to use some of it in HTML.
I'm trying to make this script run every 34 seconds, however I don't know how to loop it as such.
Here's my script:
function byId(id){
return document.getElementById(id)
}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {
setTimeout(function() {
byId('audioID').play()
}, 13000);
}
However I don't know how I would loop this every 34 seconds, after it starts at 13 seconds.
Thanks!
setTimeout makes the script run after x miliseconds, if you want to run the script multiple times, you need to use setInterval instead.
setInterval( function(){ byId('audioID').play() }, 34000 );
If I understand correctly, you want to start the interval after 34 seconds, so you need to do this instead:
setTimeout(function(){
//Declaring the function within this code scope just for DRY purposes
var runFn = function(){
byId('audioID').play();
}
runFn(); //runs the function once before the interval starts.
setInterval(runFn, 34 * 1000 );
}, 13 * 1000);
Create a new function who will execute byId('audioID').play() every 34Secs
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {}
function byId(id) {
console.log(id);
return document.getElementById(id);
}
const loopTime = 34000; //34000 ms = 34secs
var startProcess = function() {
setInterval(function() {
byId('audioID').play();
}, loopTime);
};
setTimeout(startProcess, 13000);
This works. If you need to stop the interval just call clearInterval(interval).
var interval;
setTimeout(function(){
console.log("Started interval after 1 sec");
interval = setInterval(function(){
console.log("hai")},2000)
},1000);

javascript setTimeout function does not work

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);

How can I call a function every 3 seconds for 15 seconds?

How do I call a jQuery function every 3 seconds?
$(document).ready(function ()
{
//do stuff...
$('post').each(function()
{
//do stuff...
})
//do stuff...
})
I'm trying to run that code for a period of 15 seconds.
None of the answers so far take into account that it only wants to happen for 15 seconds and then stop...
$(function() {
var intervalID = setInterval(function() {
// Do whatever in here that happens every 3 seconds
}, 3000);
setTimeout(function() {
clearInterval(intervalID);
}, 18000);
});
This creates an interval (every 3 seconds) that runs whatever code you put in the function. After 15 seconds the interval is destroyed (there is an initial 3 second delay, hence the 18 second overall runtime).
You can use setTimeout to run a function after X milliseconds have passed.
var timeout = setTimeout(function(){
$('post').each(function(){
//do stuff...
});
}, 3000);
Or, setInterval to run a function every X milliseconds.
var interval = setInterval(function(){
$('post').each(function(){
//do stuff...
});
}, 3000);
setTimeout and setInterval return IDs, these can be used to clear the timeout/interval using clearTimeout or clearInterval.
setInterval(function() {
// Do something every 3 seconds
}, 3000);
Use the setInterval function.
var doPost = function() {
$('post').each(function() {
...
});
};
setInterval(function() { doPost(); }, 3000);
You could use the setTimeout method also, which supports things like cancelling the timer.
See: http://msdn.microsoft.com/en-us/library/ie/ms536753(v=vs.85).aspx

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