I am trying to run a function when the value of a variable changes. So far I am using setInterval
for this but that is not good.
Is setInterval
actually used in production at all or is that bad practice? Will it fill up the page with events in the browser cache and make the page slower the longer a user is on it?
This question talks about getters and setters but unfortunately I have difficulties understanding how those work and would be super happy about a jsFiddle or an explanation for a JS beginner.
This is what I am using now. If you resize the executing window the event will also trigger so you can actually use this jsFiddle without zooming the viewport.
var currentZoom = screen.width / window.innerWidth;
function getZoomValue() {
var screenWidth = screen.width;
var windowWidth = window.innerWidth;
// http://www.quirksmode.org/mobile/viewports2.html
var zoomLevel = screenWidth / windowWidth;
//console.log(zoomLevel);
if (currentZoom != zoomLevel) {
alert('zoom value/level changed to '+zoomLevel);
}
currentZoom = zoomLevel;
}
getZoomValue();
setInterval(getZoomValue, 1000);
How can I use a getter and setter for this scenario please?
This answer mentions using a global variable but there I do not understand how I can add the zoomLevel
value to the global variable, plus using global variables is also bad practice, right?
Also, it says using Object.watch is not good, so I guess to really check cross-browser if a value of a variable has changed is to use a getter and setter, right?
I have checked and read through these three questions for research but I am still missing bits in my understanding. An explanatory answer with a possible jsFiddle would be highly appreciated.
edit
People are pointing out in the comments that I should check the zoomLevel
on resize event and that it won't change its value. Unfortunately it will indeed change its value if the user resizes the viewport.
window.addEventListener('resize', function(e) {
var zoomLevel = screen.width / window.innerWidth;
console.log(zoomLevel);
});
So if I attach the function to get the zoomLevel
the resize event I will also get values despite real zooming is not happening. This is pointed out in this comment.
Also Chrome and Firefox for Android do not fire resize events on zoom/pinch, only on orientation change, so getting the zoomLevel
from the resize event also does not work in this scenario.
So how can I separate the window resize event results from the real zoom change event results and actually get the zoomLevel
either with or without attaching it to the resize event?