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);
Related
I'm trying to make a game, and it needs to keep looping for X seconds of time, preferably something that I can change.
var startTime = Date.now();
while ((Date.now() - startTime) < guessTheWordDuration) {
//game code
}
I have tried this but it does not seem to work, setting it to one number just seems to loop it infinitely.
Any help is appreciated!
This is in nodejs v8
How often do you need the while loop to tick? I would maybe do something like this.
function gameLoop () {
// do stuff
setTimeout(() => {
gameLoop();
}, 100); // makes the thread non blocking for 100 ms
}
gameLoop();
Then you just have to create a variable for your timeout and cancel it if you'd like to stop the loop.
I use Express framework, I have this function and I want to run it in intervals since server starts:
setTimeout(function () {
console.log('timeout completed');
}, 1000);
so i put this piece of code to the initial file of Express.js Framework called App.js but it only runs twice, where is the problem and how could I fix it?
The setTimeout function runs only once when that amount of time is completed,
here in your case it is 1s(1000ms).
Instead you may want to use setInterval which does the same thing except that it doesn't stop until you tell it so.
Here is an example :
var max = 3;
var i = 0;
var timer = setInterval(function(){
if(i === max){
// stop the timer from looping.
clearInterval(timer);
}else{
i++;
}
},1000);
Looks like you are describing a cron sort of job, why don't you use any of the many node crons modules instead.
https://www.npmjs.com/package/node-cron
Check that out, pretty straight forward.
I have this function:
isAuthenticated = (): boolean => {
xxx
};
I am using AngularJS and I would like to know how can I make a function such as
keepCheckingAuthentication()
That will call the is Authenticated() function every 60 seconds?
There’s a setInterval function that will call any code with given time interval in ms:
var intervalID = setInterval(function() { console.log('Works!') }, 1000);
Later you can cancel the timer using clearInterval(intervalID).
If isAuthenticated can be modified to actually make a request to call the server in order to check authentication, and can return a promise that resolves or rejects when this is done, then I would do something like
var keepCheckingAuthentication = function() {
return isAuthenticated().catch(angular.noop).then(function(isAuth) {
// Can do something different if isAuth == false
return $timeout(keepCheckingAuthentication, 60 * 1000);
});
});
Note the call to catch. This effectively converts any rejections to a success, so the next then callback runs in every case.
Using something like this rather than $setInterval means there will always be 60 seconds between responses from the server, rather than requests made. On a slower connection, or an overloaded server, this means there is a lower chance of adding to the overloaded connection or server, as you're sure the previous request has finished before sending off another one.
you can probably use $interval function (wrapper of window.setInterval() in AngularJS)?
The documentation of $interval function is here
In your case keepCheckingAuthentication() is the function and you can adjust the other parameters accoding to your needs? Does this help?
example:
$interval(myFunctionAtInterval, 5000) // Scheduled for every 5 seconds, for instance
funtion myFunctionAtInterval() {...}
I tend to avoid setInterval whenever I can, i.e. always (Paul Irish talks about this in this video).
What I do is wrap a setTimeout in a function that recursively calls itself (with a condition that allows me to easily stop, or to let the data decide when it's not needed anymore).
var condition = true;
$scope.count = 1;
function myFunc(){
$scope.count += 1;
}
var timer = function(){
myFunc();
if( condition ){
$timeout(timer, 1000);
}
};
timer();
I am using angular built in $timeout here as it's always suggested.
A demo
use $interval.this code will help you:
var callefunc=function() {
console.log('hey i am calle');
}
$scope.caller=function(){
var stop = $interval(callefunc, 1000);
}
here you can call a caller function when you want to start function callefunc on interval of 1 second .
I'm pretty new to (javascript) programming and I'm trying to get something automated.
There is a page that contains a countdown timer, and I want my greasemonkey script to automatically do some actions if the condition is met.
I've got this right now:
var timer = document.getElementById('timer_4975');
if (timer.innerHTML < "00:00:20"){
//Some actions
}
But this only checks the condition once when the script is loaded, when the timer goes under 00:00:20, it doesn't detect the condition is met and doesn't go to action.
Can someone guide me in the right direction?
Thanx in advance!
You can use the setTimeout or setInterval functions to perform this task.
setInterval will perform a task regularly, which is probably more suited to what you want to achieve.
Something like:
var timer = document.getElementById('timer_4975');
var intervalHandle = setInterval(function() {
if (timer.innerHTML < "00:00:20"){
//Some actions
clearInterval(intervalHandle);
}
},1000);
would check every second (1000ms). Change the 1000 value to increase or decrease the frequency of checking... once a second is likely to be often enough.
You will have to use setInterval() to execute your code more than once:
setInterval(function() {
if(timer.innerHTML < "00:00:20") {
//Some actions
}
}, 5000); //Execute this function each 5 seconds.
I've searched for how to use setTimeOut with for loops, but there isn't a lot on how to use it with while loops, and I don't see why there should be much difference anyway. I've written a few variations of the following code, but this loop seems to crash the browser:
while(src == '')
{
(function(){
setTimeout(function(){
src = $('#currentImage').val();
$("#img_"+imgIdx).attr('src',src);
}, 500);
});
}
Why?
Basically I have an image created dynamically whose source attribute takes time to load at times, so before I can display it, I need to keep checking whether it's loaded or not, and only when its path is available in $('#currentImage'), then do I display it.
This code worked fine before I used a while loop, and when I directly did
setTimeout(function(){
src = $('#currentImage').val();
$("#img_"+imgIdx).attr('src',src);
}, 3000);
But I don't want to have to make the user wait 3 seconds if the loading might be done faster, hence I put the setTimeOut in a while loop and shorted its interval, so that I only check for the loaded path every half second. What's wrong with that?
The while loop is creating trouble, like jrdn is pointing out. Perhaps you can combine both the setInterval and setTimeout and once the src is filled, clear the interval. I placed some sample code here to help, but am not sure if it completely fits your goal:
var src = '';
var intervalId = window.setInterval(
function () {
if (src == '') {
setTimeout(function () {
//src = $('#currentImage').val();
//$("#img_" + imgIdx).attr('src', src);
src = 'filled';
console.log('Changing source...');
clearInterval(intervalId);
}, 500);
}
console.log('on interval...');
}, 100);
console.log('stopped checking.');
Hope this helps.
The problem is probably that you're not checking every half second.
setTimeout schedules a function to run at a future time, but it doesn't block, it just runs later. So, in your while loop you're scheduling those functions to run just as fast as it can iterate through the while loop, so you're probably creating tons of them.
If you actually want to check every half second, use setInterval without a loop instead.
Thanks everyone - all the suggestions helped. In the end I used setInterval as follows:
var timer;
// code generating dynamic image index and doing ajax, etc
var checker = function() {
var src = $('#currentImage').val();
if(src !== '') {
$('#img_' + imgIdx).attr('src', src);
clearInterval(timer);
}
};
timer = setInterval(checker, 500);