How can I run a Javascript function with per-set time delays, without using any framework?
I have a Ajax script which will fetch the no of online users from server. This script i want to run in a regular timed delays.
Thanks in advance.
The simplest way would be with setInterval:
setInterval(function() {
console.log("run every second");
}, 1000);
This will run the given code at the specified time interval over and over.
var interval = window.setInterval(function() {
console.log("foo");
}, 1000);
And stop
window.clearInterval(interval);
You can use setInterval to do this.
See: https://developer.mozilla.org/en/DOM/window.setInterval
var int = self.setInterval(askQuestion,1000);
function askQuestion() {
// do something... code to be implemented.
}
Will be call askQuestion() every 1000 milliseconds (1 seconds) for example..
<script>
var intervalVariable=setInterval(function(){
//Your operation goes Here
},1000); // executes every 1000 milliseconds(i.e 1 sec)
function stopTimer()
{
clearInterval(intervalVariable); // To clear TimerInterval/stop the setInterval Function
}
</script>
Related
I run a function in Javascript asynchronously by using the setinterval function.
myVar = setInterval(myTimer, 5000);
The execution of the myTimer function can be quite long, sometimes longer than the specified delay, in that case the intervals just get executed back to back. I would like the next execution of the callback function to be scheduled in relationship with the end of the execution of the previous. To restate I want the myTimer function to run after 5000 ms of when previous finishes and wanted this to repeat.
Yes this can be done using setTimeout instead.
function myTimer(){
console.log("Exec func");
// Rest of the functionality here
setTimeout(myTimer, 5000);
}
myTimer();
You can do something like that:
function longFunction() {
// Do your stuff here
}
var taskId;
function task() {
longFunction();
taskId = setTimeout(task, 5000);
}
If I call the update function several times I get multiple instances of this interval running. How can I be sure that this only gets triggered once per idVar?
For example if I run this twice in a row with the same idVar I get two updates per second, where it should only be one.
If the idVar is different it should run multiple times. idVar is used in Update().
intervals[idVar] = setInterval(function() {
update();
}, 1000);
intervals[idVar] = setTimeout(function() {
update();
}, 1000);
If you really need to use setInterval and dont want to use setTimeout , you can clear it when you enter function
For example
var interval
interval = setInterval(function(){
clearInterval(interval)
//Your code
});
If you really want a new instance of the interval running for each unique idVar, you just need to check to see if you already have an instance of the interval running for the current idVar:
if (!intervals[idVar]) {
intervals[idVar] = setInterval(function() {
update();
}, 1000);
}
setInterval returns a timeoutID that is used to identify it.
To stop a setInterval you pass it's timoueID to clearInterval.
Explanation of why you get two intervals running
When you do this:
intervals[idVar] = setInterval(function() { update(); }, 1000);
intervals[idVar] = setInterval(function() { update(); }, 1000);
What you are doing is:
call your first setInterval and setting intervals[idVar] to this first setInterval's timeoutID
call your second setInterval and overwrite the value stored in intervals[idVar] with the timeoutID of your newly called
setInterval
Result: Two seperate intervals, with intervals[idVar] storing the timeoutID of the second one called
setTimeout
setTimeout is like setInterval and actually uses the same pool of timeout IDs, but it is only invoked once after the specified delay.
Setting one interval (setTimeout or setInterval) per idVar
var idVar = setInterval(function() {
update();
}, 1000); // sets idVar to the timeoutID and starts the interval
}
intervals[idVar] = idVar; // assigns a property 'idVar' on `intervals`
// and sets the timeoutID as its value
// allows you to call clearInterval(intervals[idVar]);
However, without knowing exactly what your update() method is doing it is difficult to tell what the best solution would be here...
I have an ongoing while loop. In the while loop, there is a setTimeout(). I want to reset the timer AFTER the timer expires. In other words, when timer expires, it should do some specified actions, and then freshly start the timer again.
For example, in the following code, %%--Hi--%% should be printed only ONCE in 5 seconds. However, after 5 seconds, %%--Hi--%% is printed continuously. I tried clearTimeout but it looks like that clearTimeout can stop timer only before timer expires.
while(){
var timeoutHandle = setTimeout(function() {
console.log("%%--Hi--%%");
clearTimeout(timeoutHandle);
},
5000); //5 sec
}
Help please! Thanks!
It's not the timeout that's tripping you up, it's the infinite while loop. You're effectively creating thousands of timeouts every second. Moving the timeout outside of the infinite loop should solve your problem.
function timedAction() {
// your timed actions to be invoked every 5 seconds
setTimeout(timedAction, 5000); // start the next timeout
}
setTimeout(timedAction, 5000); // start the first timeout
while() {
// your continuously executing actions
}
There is no need to clear a timeout after it expires.
Alternatively you could also use setInterval, simplifying your code as follows:
function timedAction() {
// your timed actions to be invoked every 5 seconds
}
setInterval(timedAction, 5000); // start the interval
while() {
// your continuously executing actions
}
try this code:
logFun();
function logFun() {
console.log("%%--Hi--%%");
setTimeout(logFun, 5000);
}
or, you can try setInterval:
setInterval(function () {
console.log("%%--Hi--%%");
}, 5000);
The setTimeout method does not act like a sleep statement. Your while loop will continue to iterate continuously regardless of what time interval you set in the setTimeout method.
You should remove the while and simply use setInterval(). (Mentioned in yibuyisheng's answer. +1)
var myInterval = setInterval(function () {
console.log("%%--Hi--%%");
}, 5000);
If you want to stop the interval, run the following:
clearInterval(myInterval);
Your problem is that setTimeout is an asynchronous function, so your code doesn't wait for it to finish before looping again. To get around this you have to create your new timer inside the previous timer.
Likewise you have to call any actions you want to execute from inside the timer and can't just call them from in the while loop, because they won't wait for the timer to finish.
function logFun() {
console.log("%%--Hi--%%");
// execute actions
setTimeout(logFun, 5000);
}
This is what yibuyisheng has done with his answer that just showed up. (Still posting because the answer was not explained.)
Alternatively, if you must create the setTimeout() from the while loop, you could have a boolean (true/false) lock it. This is not as clean as yibuyisheng's answer, but it also allows you to add as much logic as you'd like to control enabling and disabling the timeout.
Example:
window.isTimeoutLocked = false;
while(true) {
if (!window.isTimeoutLocked) {
var myFunction = function () {
console.log("%%--Hi--%%");
//The timeout has fired. Unlock it for the next one.
window.isTimeoutLocked = false;
}
window.setTimeout(myFunction, 5000);
//Timeout is queued. Lock this code until the timeout fires.
window.isTimeoutLocked = true;
}
}
Also, I doubt that an infinite while loop is best for your upstream code. There is probably a callback that you can hook into, like requestAnimationFrame or some relevant event.
I'm trying to create a new scheduled report and I've one doubt about it: How can I create a script on it with a loop that runs a function every 10 seconds? Something like:
var value = 1;
while(value > 0){
setTimeout(function(){myFunction()},10000);
value = value -1;
}
When I just run my report into the report studio (without schedule) this script executes successfully, but after the schedule it doesn't work anymore. Someone know why is this happening or have any other idea?
Thanks in advance.
If you want to keep the same structure, you can use setTimeout to make it slightly recursive:
var repeatedFunction = function(){
// Do something
setTimeout(repeatedFunction, 10 * 1000);
};
but you're better off using setInterval:
setInterval(function(){
// do something
}, 10 * 1000);
and if you need to cancel it, store the interval:
var repeatedFunction = setInterval(function(){
// do something
}, 10 * 1000);
// .. something happened; need to cancel
clearTimeout(repeatedFunction);
Use setInterval instead of setTimeout.
Also your while loop is not needed.
Just use this instead:
setInterval(myFunction, 10000);
how can I execute a javascript program 30 after page loads, and I have to execute it repeatedly in 30 seconds. I would like to use jquery since I already included in my document
Thank you guys
You could use the window.setTimeout method:
window.setTimeout(function() {
// This will execute 30s after the page loads
// and it will execute only once
}, 30000);
If you want to repeat the execution of the function on every 30 seconds you could use the setInterval method.
As far as jquery is concerned you don't need to to use it for such a simple task as it is already built into javascript.
You want setInterval() here, like this:
setInterval(function() {
alert("It's been 30 seconds");
}, 30000);
setInterval() will fire after the delay (so 30 seconds in) then again every time the delay is up (every 30 seconds as desired).
If you want to execute it 30 times, once a second, you'd use setInterval.
var interval = window.setInterval(function() {
// do stuff
}, 1000);
window.setTimeout(function() {
window.clearInterval(interval);
}, 30 * 1000);
$.ajaxSetup({
cache: false
});
setInterval(function() {
$("#data1").load('1.php');
}, 30000);
});
Just substitute your jQuery function in :)