I think I might be overtired but I cannot for the life of me make sense of this, and I think it's due to a lack of knowledge of javascript
var itv=function(){
return setInterval(function(){
sys.puts('interval');
}, 1000);
}
var tout=function(itv){
return setTimeout(function(){
sys.puts('timeout');
clearInterval(itv);
}, 5500);
}
With these two functions I can call
a=tout(itv());
and get a looping timer to run for 5.5 seconds and then exit, essentially.
By my logic, this should work but it simply is not
var dotime=function(){
return setTimeout(function(){
clearInterval(function(){
return setInterval(function(){
sys.puts("interval");
}, 1000);
});
}, 5500);
}
any insight in this matter would be appreciated.
it cannot work because because your setInterval will be called AFTER the timeout! your original approach is correct and you can still wrap this into single function:
var dotime=function(){
var iv = setInterval(function(){
sys.puts("interval");
}, 1000);
return setTimeout(function(){
clearInterval(iv);
}, 5500);
};
I think the mistake you're making is that the function itv doesn't return setInterval(function(){ sys.puts('interval'); }, 1000) it executes setInterval(function(){ sys.puts('interval'); }, 1000) and than returns back an ID that setInterval generates. That ID is then passed to the clearInterval function to stop what setInterval(function(){ sys.puts('interval'); }, 1000) is doing.
Edit: An example of one function that would work.
var dotime=function(){
// Start our interval and save the id
var intervalId = setInterval(function(){
// This will get executed every interval
sys.puts("interval");
}, 1000);
// Start our timout function
setTimeout(function(){
// This will get executed when the timeout happens
clearInterval(intervalId); // Stop the interval from happening anymore
}, 5500);
}
This is another way to write your version, you see that you pass a function to clearInterval, where you should have passed it a timer id.
var dotime=function(){
var g=function(){
var f=function(){
return setInterval(function(){
sys.puts("interval");
}, 1000);
}
clearInterval(f);
}
return setTimeout(g, 5500);
}
To make it work you shoud call the function :
clearInterval(f());
Or, using your version :
var dotime=function(){
return setTimeout(function(){
clearInterval(function(){
return setInterval(function(){
sys.puts("interval");
}, 1000);
}());
}, 5500);
}
Disclaimer : I didn't test this.
Related
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");
}
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);
I have a strange problem, well I'm trying to make a loop using setInterval but i want to have a SetTimeout inside as well.
Seems, from the comments, what you need is just
var init = function() {
setTimeout(function(){
console.log("Hi");
init(); // only call init here to start again if need be
}, 8000);
}
init();
based on the comment below, I'm assuming the interval needs to be "paused" sometimes because in your comment you say at some point, I have to delay one action - which implies that this delay isn't always necessary. Given that, you could write it as follows
var test = function() {
var interval = setInterval(function() {
if (someCondition) {
clearInterval(interval); // stop the interval
setTimeout(function(){
console.log("Hi");
test(); // restart the interval
}, 8000);
} else {
// this is done every second, except when "someCondition" is true
}
}, 1000);
}
or even
var running = true;
var test = function() {
var interval = setInterval(function() {
if (someCondition) {
running = false; // stop the interval
setTimeout(function(){
console.log("Hi");
running = true; // restart the interval
}, 8000);
} else if (running) {
// this is done every second, only when "running" is true
}
}, 1000);
}
myInterval = setInterval(function(){
MyFunction();
},50);
function MyFunction()
{
//Can I call clearInterval(myInterval); in here?
}
The interval's not stopping (not being cleared), if what I've coded above is fine then it'll help me look elsewhere for what's causing the problem. Thanks.
EDIT: Let's assume it completes a few intervals before clearInterval is called which removes the need for setTimeout.
As long as you have scope to the saved interval variable, you can cancel it from anywhere.
In an "child" scope:
var myInterval = setInterval(function(){
clearInterval(myInterval);
},50);
In a "sibling" scope:
var myInterval = setInterval(function(){
foo();
},50);
var foo = function () {
clearInterval(myInterval);
};
You could even pass the interval if it would go out of scope:
var someScope = function () {
var myInterval = setInterval(function(){
foo(myInterval);
},50);
};
var foo = function (myInterval) {
clearInterval(myInterval);
};
clearInterval(myInterval);
will do the trick to cancel the Interval whenever you need it.
If you want to immediately cancel after the first call, you should take setTimeout instead. And sure you can call it in the Interval function itself.
var myInterval = setInterval(function() {
if (/* condition here */){
clearInterval(myInterval);
}
}, 50);
see an EXAMPLE here.
var interval = setInterval(function() {
if (condition) clearInterval(interval); // here interval is undefined, but when we call this function it will be defined in this context
}, 50);
Or
var callback = function() { if (condition) clearInterval(interval); }; // here interval is undefined, but when we call this function it will be defined in this context
var interval = setInterval(callback, 50);
From your code what seems you want to do is to run a function and run it again and again until some job is done...
That is actually a task for the setTimeout(), the approach is similar:
var myFunction = function(){
if( stopCondition ) doSomeStuff(); //(do some stuff and don't run it again)
else setTimeout( myFunction, 50 );
}
myFunction(); //immediate first run
Simple as that :)
Of course if you REALLY want to use setInterval for some reason, #jbabey's answer seems to be the best one :)
You can do it by using a trick with window.setTimeout
var Interval = function () {
if (condition) {
//do Stuff
}
else {
window.setTimeout(Interval, 20);
};
};
window.setTimeout(Interval, 20);
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