Turbolinks: How to stop running functions when you leave the page? - javascript

In my Rails 5.2.2 app I am using Turbolinks.
I have discovered that when I leave a page, the functions that were started continues.
I have organised my functions below a return statement that checks the body class. In my example below, if the body class is not foobar the functions below do not run.
// assets/javascripts/pages/foobar.js
var goLoop;
$(document).on("turbolinks:load", function() {
if (!$("body").hasClass("foobar")) {
return;
}
return goLoop();
});
goLoop = function() {
return setTimeout((function() {
console.log("Hello");
return goLoop();
}), 1000);
};
First time I visit the page, the goLoop function is triggered.
When I follow a link away from the page, the function runs. If I had not used Turbolinks, this would not have happened.
If I follow another link back to the page, the function is triggered again, so now it runs twice.
How can I avoid this, without disabling Turbolinks?

Use the turbolinks:before-cache to teardown your timeout using clearTimeout. You will need to keep a reference of the current timeout ID. So your solution might look like:
var goLoop;
var timeout;
$(document).on("turbolinks:load", function() {
if (!$("body").hasClass("foobar")) {
return;
}
return goLoop();
});
goLoop = function() {
return timeout = setTimeout((function() {
console.log("Hello");
return goLoop();
}), 1000);
};
$(document).on("turbolinks:before-render", function() {
clearTimeout(timeout);
});

You can use PageVisibilityAPI to see is current page active or not.
and for the loop issue, you should check whether it's exist or not then run timeout function.

Related

Boolean statement not evaluating in javascript

I'm writing a script, and there are two boolean statements that are very similar but giving different results, and I don't see why they conflict with one another.
My function looks like this:
SCRIPT:
(function() {
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
if (stopped) {
setInterval(function() {
console.log("The timer is working.");
}, 1000);
}
button.addEventListener('click', function(){
if (stopped) {
stopped = false;
console.log(stopped);
} else {
stopped = true;
console.log(stopped);
}
});
}
}
}).call(this);
The basic idea is that when I push the button the setInterval function stops, however it keeps on going even when the if/else function switches stopped to false.
For example, my console.log looks like this:
I.e. stopped = false, but setInterval doesn't terminate.
Why is this not evaluating correctly?
The problem with your code is that you are trying to work on a piece of code that has already started to operate. In simpler words, the setInterval method will be called every 1000ms, no matter what the value of stopped variable is. If you wish to really stop the log, you can do any of these:
clearInterval()
to completely remove the interval or
setInterval(function() {
if (stopped) {
console.log("The timer is working.");
}
}, 1000);
to check if the value of stopped variable has changed or not (after the click) and act accordingly. Choose either of these for your purpose..
you are calling setinterval even before button is clicked .As the event is already triggered you cannot stop just by setting the variable to false ,you need to clear the interval using clearinterval
check the following snippet
var intervalId;
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
var Interval_id;
button.addEventListener('click', function() {
if (stopped) {
Interval_id = callTimeout();
stopped = false;
} else {
clearInterval(Interval_id);
stopped = true;
}
});
}
function callTimeout() {
intervalId = setInterval(function() {
console.log("The timer is working.");
}, 1000);
return intervalId;
}
<input type="button" id="start-stop" value="click it">
Hope it helps
Put the if(stopped) statement inside the setInterval function because if you used this function once it will keep going..
Another way to stop setInterval function is by using clearInterval, like this
var intervalId = setInterval(function() { /* code here */}, 1000)
// And whenever you want to stop it
clearInterval(intervalId);
When you click the button stopped variable becomes false but the setInterval will not stop because the setInterval code is already executed.. it will not execute again on button click. And if you reload the page what will happen is that stopped variable will be again set to true as you have written at first line and setInterval will execute again ..
Now What you can do is store setInterval in a variable like this
var timer = setInterval(function,1000);
and then when you click the button use this method to clear interval
clearInterval(timer);
this should do the trick .. Hope it helps ..

In jQuery how to wait for specific value on variable

I have an variable
var IsAjaxing;
I set it to true everytime a ajax is fired on the page. And then set it to false when ajax is finished;
I am building a SafeAjaxing event so work would only be done when the page is not ajaxing:
// safe-ajaxing: Triggers when no ajax is running
$($fieldRenderPageDOM).on("safe-ajaxing", '.field-render', function(e, work) {
$.when({ IsAjaxing: false }).done(work);
});
This doesn't seem to wait, work is always called immediately.
It would be called like this:
$fieldDOM.trigger("safe-ajaxing", function () {
$fieldDOM.trigger("do-work");
$fieldDOM.trigger("do-some-more-work);
});
You should use promises for this purpose:
var IsAjaxing = function(){
var defer = $.Deferred().resolve();
return {
On: function(){
defer = $.Deferred();
},
Off: function(){
defer.resolve();
},
Promise: function() {
return defer.promise();
},
IsOn: function() {
return defer.state() == "pending";
},
IsOff: function() {
return defer.state() != "pending";
}
};
}();
And then your event will be:
// safe-ajaxing: Triggers when no ajax is running
$($fieldRenderPageDOM).on("safe-ajaxing", '.field-render', function(e, work) {
$.when(IsAjaxing.Promise()).done(work);
});
Each time when you start ajax request run:
IsAjaxing.On();
Each time when you finish ajax run:
IsAjaxing.Off();
To check the current state of IsAjaxing, call the IsOn and IsOff function.
This might not be the best way, but it works.
You really should optimize the code i've written, but this is to get you started.
var isAjaxing = false;
var check = function(){
if(isAjaxing){
// do something
alert();
// freeze the checking
// manual restart is required
clearInterval(interval);
}
}
var interval = setInterval(check, 10);
// to demonstrate the variable change
setInterval(function(){
isAjaxing = true;
}, 3000);
This scripts checks if the variable is changed every 10 miliseconds.
Note: The clearInterval() function is used to stop checking.
I am building a SafeAjaxing event so work would only be done when the page is not ajaxing.
Don't build this yourself. Just use the builtin ajax events of jQuery, namely
ajaxStart "This event is triggered if an Ajax request is started and no other Ajax requests are currently running."
ajaxStop "This global event is triggered if there are no more Ajax requests being processed."

How to start javascript setinterval once cleared?

I have a setinterval that runes every 5 seconds. this works fine on page load.
I have the following scenarios:
Load page with interval (WORKS)
press button and load new content and stopp interval(WORKS)
Once the new content is no longer desiered, dissmiss it, return to first content and start interval again(DOES NOT WORK)
I have saftys suchs as events for window.blur that also stops the interval so that the browser does not commponsate for all the missing intervals if i would change tabs or something. Keep in mind that step 3 did not work BUT if i would after step 3 change a tab and then return to my original page(execute blur) the interval would start working again.
NOTE all content loading here exept page load is done with ajax calls.
My code:
initializing:
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function() {
$.automation.tanks.tableInit();
});
binding function:
bindIntervalEvent: function (target, url, callback) {
$(window)
.on("focus.mine",
function() {
$.automation.worker.setUpdateInterval(target, url, callback);
})
.on("blur",
function() {
$.automation.worker.stopUpdateInterval();
}).trigger("focus.mine");
}
interval function:
setUpdateInterval: function (target, url, callback) {
if ($.automation.globals.globalInterval.value.length === 0) {
$.automation.globals.globalInterval.value.push(window.setInterval(
function () {
var options = {
loadTarget: target
}
$.automation.worker.getView(url,
function() {
if (callback)
callback();
},
options);
},
5000));
}
}
the function that stops the interval:
stopUpdateInterval: function () {
if ($.automation.globals.globalInterval.value.length === 0)
return;
console.log("deleting");
for (var i = 0; i <= $.automation.globals.globalInterval.value.length; i++) {
window.clearInterval($.automation.globals.globalInterval.value[i])
$.automation.globals.globalInterval.value.splice(i, 1);
console.log($.automation.globals.globalInterval.value.length);
}
}
when stopping the interval i also remove the window bindings:
unBindIntervalEvent: function() {
$(window).off("focus.mine");
$(window).unbind("blur");
}
Back to step 3:
My sucess method in the callback to my getviewfunction is identical to what i execute in the beginning
code:
$(".updatelatest")
.on("click",
function () {
var _this = $(this);
var options = {
loadTarget:"#TanksContent"
}
$.automation.worker.getView("/Tank/GetTanks",
function (data) {
$(_this).switchClass("col-md-5", "col-md-1", 1000, function() {
$(_this).addClass("hidden");
$(".search").switchClass("col-md-5", "col-md-12", 1000, "easeInOutQuad");
})
$.automation.tanks.tableInit();
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
$.automation.tanks.tableInit();
});
$(window).trigger("blur");
}, options);
});
but this does not start the interval. it is clearly initialized since it works when window.blur is executed for example when I change tab but for some reason this is not working beyond that.
i tried triggering the windows blur event and nothing happened, i tried triggering my custom window event "focuse.mine" but nothing happens.
I did not notice this while developing since I had firebug open and every time i checked scripts or css or the console the blur function was executed so I assumed that my code worked as intended but now that it is deployed I notice this.
My head is pounding beyond reason and I can't for figure out where I have gone wrong.
Well this was a fun one. I simply found that when calling the setUpdateInterval(); function directly it gave me the desiered result.
I realized that the reason I had them split like I did was becaouse of the blur event. "Focus.mine" is triggered to start the inteval again ocne a user comes back to the page.

NightwatchJS .waitForElementPresent abortOnFailure not working

I'm using NightwatchJS with NodeJS: http://nightwatchjs.org/api
I have a modal dialog, which may or may not appear. It has a #close_button that needs to be clicked (if the modal does appear) to continue.
I set the abortOnFailure parameter of waitForElementPresent to false so the script continues if the modal does not appear. However I can't get it to work.
Any suggestions?
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false, function() {
this.click('#close_button')
})
.setValue('#username', 'test#email.com')
//more code here
.end(); //does end() go here or inside .waitForElementPresent() above?
}
}
abortOnFailure works fine, however waitForElementPresent has a bug now in which the callback you passed it's not called in the correct context. That will be fixed.
In the mean time you can write your test like this, with placing the click outside, which is the same thing and looks cleaner:
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false)
.click('#close_button')
.setValue('#username', 'test#email.com')
//more code here
.end(); // end() goes here
}
}
I ran into something similar, I was waiting for an iframe to be present. I created a function to actually close it:
pageObject function:
Home.prototype.closeIframe = function(browser) {
var self = this;
console.log('Checking for iframe');
this.browser
.isVisible(iframeSelectors.iframe, function(result) {
if (result.value === true) {
self.browser
.log('iframe visible')
.frame(iframeSelectors.name)
.waitForElementVisible(iframeSelectors.closeLink)
.click(iframeSelectors.closeLink)
.assert.elementNotPresent(iframeSelectors.iframe)
.frame(null)
.pause(2000); //allow for proper frame switching
} else {
console.log('iframe is not visible');
}
});
return this;
In my test I wait for the page to fully load before executing the above function.

Busy indicator race condition in Javascript

I have the following (javascript/jquery) code to show a busy indicator (after a delay) while an image is loading:
function imgUpdate(arg) {
var loaded = false;
$("#image").one("load", function(){
loaded = true;
$("#busyIndicator").hide();
});
setTimeout(function(){
if (!loaded) {
$("#busyIndicator").show();
}
}, 250);
$("#image")[0].src = arg;
}
Sometimes, the indicator comes up and stays up. How is this possible if the browser's javascript engine is single-threaded? (This is on Firefox 3, by the way.)
One note: this seems to happen when the image being loaded is already cached.
Another note: if I log to my firebug console, all of the lines in imgUpdate are executed, but a log message inside the onload handler never prints on subsequent calls to imgUpdate.
Is there any other javascript on the page that breaks? If so, this may not be a race condition -- JS could simply stop executing before the busyIndicator is hidden again...
I'm hard pressed to replicate this.
Here is the implementation of what you're doing:
A version using caching:
http://jsbin.com/uwuho
A version with caching being prevented: (uses parameter to avoid caching)
http://jsbin.com/oguvi
Hit F5/Ctrl-F5 to see it go. (in particular with the version which prevents caching)
With or without caching neither version is doing what you'd described.
Your problem probably lies elsewhere.
Clearing the image's src tag seems to fix the problem:
function imgUpdate(arg) {
var loaded = false;
$("#image").one("load", function(){
loaded = true;
$("#busyIndicator").hide();
});
setTimeout(function(){
if (!loaded) {
$("#busyIndicator").show();
}
}, 250);
$("#image")[0].src = "";
$("#image")[0].src = arg;
}
You might want to clear the timeout in your callback so that it won't fire if the image is loaded.
var timer = null;
function imgUpdate(arg) {
var loaded = false;
timer = setTimeout(function(){
$("#busyIndicator").show();
timer = null;
}, 250);
$("#image").one("load", function(){
if (timer) {
clearTimeout(timer);
timer = null;
}
$("#busyIndicator").hide();
});
$("#image")[0].src = arg;
}

Categories