understanding an automatic page refresh in javascript - javascript

I am trying to understand this code:
function setIdle(cb, seconds) {
var timer;
var interval = seconds * 1000;
function refresh() {
clearInterval(timer);
timer = setTimeout(cb, interval);
};
$(document).on('keypress, click', refresh);
refresh();
}
setIdle(function() {
location.href = location.href;
}, 5);
setIdle takes two arguments. Inside its function it has a function refresh that clears a timer on a Timeout function. Now every time when an event happens (click, keypress) refresh() gets called.
and then finally this function gets called passing in another function and and int value (5) which later will be the amount of seconds for the timer. In that other function which later is represented through cb the page will be refreshed (location.href = location.href;).
This causes an automaticpage refresh every 5 seconds.
So now I don't understand if I put an additional function:
setIdle(function() {
console.log('hi');
}, 1);
Why is the second function only called once and not every second like the other one?

setIdle doesn't run the callback function every 5 seconds. It runs it once, 5 seconds after you call setIdle, and if you type or click something the timeout gets pushed back again. So it runs it once, when you've been idle for 5 seconds.
The reason the page refreshes every 5 seconds is because the callback function reloads the page, and reloading the page runs all the Javascript in the page again, so that calls setIdle() again.
But your second use of setIdle doesn't reload the page, so it just logs hi once.
If you want to do something repeatedly every N seconds, use setInterval rather than setTimeout.
BTW, clearInterval should be clearTimeout. In most browser they're currently interchangeable, but there's no guarantee. See Are clearTimeout and clearInterval the same?

Related

Set delay on click event

I want to load this script after loading the page so I want to set a delay for this code to work -
document.getElementsByClassName("pdp-button_theme_bluedaraz")[0].click();
If by "delay" you mean a timer and a function which is called after the timer finishes you might want to use setTimeout() function. argument 1 is the function to be called and argument 2 is the countdown time in milliseonds eg:
setTimeout(exec, 2000);
function exec() {
document.getElementsByClassName("pdp-button_theme_bluedaraz")[0].click();
}
or if you mean execute the script after page has loaded try this
document.onload = function() {
document.getElementsByClassName("pdp-button_theme_bluedaraz")[0].click();
}

Call request animation frame every five seconds

If i need to get some new data constanly, i know that best solution is websockets.In that way the server will notify the client when there is new data. But to avoid this just for one scenario, i will need to call some http request on every five seconds.
I am using here counter just for simulation instead calling some http service.
let counter = 0;
setInterval(() => {
console.log(counter);
++counter;
},5000)
I've read that better solution is requestAnimationFrame instead of setInterval.It is more optimised by the browser and also when the tab is not active it is paused. Set interval continues to fire and when the tab is not active which is not good.
How can i call some function in requestAnimationFrame every five seconds ?
To actually only call it every 5 seconds, you'd still need (at least) setTimeout. But with this, something along the following would work:
requestAnimationFrame(function run() {
console.log('do something w/o initial delay');
setTimeout(function () {
console.log('do something w/ initial delay');
requestAnimationFrame(run);
}, 5000);
});

Calling a function by an interval in a function called by interval JS

I want to call a function that could check an amount of time constantly using an interval within function that already works (running function) by interval.
That what I had did:
var interval;
var time = prompt("Insert amount of time in seconds");
function log ()
{
console.log ("log() called.");
}
function onrunning ()
{
interval = setInterval(log,time*1000);
}
gameloop = setInterval(onrunning,5);//This interval must not cleared
The first amount of time works fine but after that it's keep calling the log() function faster and faster till the browser crashes.
I tried to do this
var interval;
var time = prompt("Insert amount of time in seconds");
function log ()
{
console.log ("log() called.");
}
function onrunning ()
{
interval = setInterval(log,time*1000);
}
gameloop = setInterval(onrunning,5);
clearInterval(interval); //tried this but no differece.
You are clearing interval in a wrong place.
In your code, you are trying to clear it before it has been created (so it's basically a no-op).
You want to clear it after it has been created and executed:
function log ()
{
console.log ("log() called.");
clearInterval(interval);
}
You should also notice that since your onrunning is also fired as an "interval" callback, you are creating new log intervals on each callback execution frame. If you want to clear this interval too, just replicate the same logic as presented above, but inside onrunning callback.
I assume you want to fire the "log" callback ("onrunning" callback as well, probably) only once after a set period of time. In that case, you should use setTimeout instead of setInterval.
This has been already pointed out by Jaromanda X in this comment.

Calling JavaScript Function that has SetTimeout Assigned to It

I'm not 100% sure how setTimeout works in JavaScript. Say I have something like this:
$(document).ready(function() {
testTimeout();
});
function testTimeout() {
alert("testing timeout");
setTimeout(testTimeout, 5000);
}
This would display a popup window every 5 after the page is ready. What would happen if then I called testTimeout from a button click?
$("#button").click(function() {
testTimeout();
});
Would the button click call testTimeout and add another timeout every 5 seconds? Or, would the button click reset the timeout from when the button was pressed? The reason I am asking is because I would like to design something like this where I can pass a parameter to my timeout function. When the web page starts up, I have a default parameter. However, if I press a button, I would like my timeout function to be called right away and every 5 seconds after with my new parameter. But, I don't want the timeout function with the old parameter to continue repeating. How can I achieve this? Any help and understanding would be greatly appreciated.
This would display a popup window every 5 after the page is ready.
No it wouldn't, it would show an alert repeatedly with no delay and/or cause a "too much recursion" error, because setTimeout(testTimeout(), 5000) calls testTimeout and passes its return value into setTimeout, just like foo(bar()) calls bar and passes its return value into foo.
If you remove the ():
function testTimeout() {
alert("testing timeout");
setTimeout(testTimeout, 5000);
// here --------------^
}
Then it would do that.
What would happen if then I called testTimeout from a button click?
You'd end up with the function being called twice as often (more than once every 5 seconds), because every time you call it, it reschedules itself. A third time would make it more frequently still (three times/second), and so on.
If you want to avoid that, one option is to remember the timer handle and cancel any outstanding timed callback if you call the function before then:
var handle = 0;
function testTimeout() {
clearTimeout(handle); // Clears the timed call if we're being called beforehand
alert("testing timeout");
handle = setTimeout(testTimeout, 5000);
}
(I initialized handle with 0 because calling clearTimeout with a 0 is a no-op.)
Have you tried to asign variable to your setinterval;
var foo = setTimeout(testTimeout(), 5000);
and then when right event comes just destroy that variable.
clearInterval(foo);
And now you can asign it again...
In your case it would simply repeat endlessly, because you're executing the function instead of passing the reference. You should do it like this:
function testTimeout() {
alert("testing timeout)";
setTimeout(testTimeout, 5000);
}
Note the missing braces after testTimeout. This tells setTimeout to execute that function, instead of the result of that function, which is how your original code behaved.
" I would like my timeout function to be called right away and every 5 seconds after with my new parameter. But, I don't want the timeout function with the old parameter to continue repeating "
In order to achieve what you're trying to do you should remove the timeout:
var timeoutId;
function testTimeout() {
alert("testing timeout)";
clearTimeout(timeoutId );
timeoutId = setTimeout(testTimeout, 5000);
}
Notes:
You can stop the previous timeoutI from firing by catching the id returned from the setTimeout method and passing that to the clearTimeout method

Trigger a function only once inside a continously triggered function

I have a function which is triggered on every mouse-down event when the mouse pointer is over the image.
Now, I call two functions in this mouse-down function.
I need one function Triangulate() be called every time and the other one ImageCalculation() last time only.
Here last time only means, a gap of minimum 3 seconds or more should be there between consecutive img_mouse_down() function calls.
Below is my code:
function img_mouse_down(){
if(leftMouseButton){
Triangulate(); //Call this function every time.
ImageCalculation(); //Call this function only the last time
}
}
If I click over the image 5 times continuously and then pauses for 3 or more seconds, Triangulate() should be called 5 times and the ImageCalculation() should be called only once.
How to achieve this?
var glob_timeout_holder;
function img_mouse_down(){
if(leftMouseButton){
Triangulate(); //Call this function every time.
clearTimeout(glob_timeout_holder); //clear if any previous continuing timeouts
glob_timeout_holder = setTimeout(ImageCalculationlast, 3000);
}
}
This may help you, as far as I understood. Everytime img_mouse_down() run, it will set a timeout to execute ImageCalculation(), but just before that kill any previous timeOuts, result is, if user stop clicking, ImageCalculation() will be called once 3 seconds after last click.
Something like that should address your problem. The timeout is cleared on every call and otherwise ImageCalculation is triggered after 3 seconds.
var timer = null
function img_mouse_down () {
if(leftMouseButton){
Triangulate();
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(function () {
ImageCalculation()
}, 3000)
}
}

Categories

Resources