I have seen this question asked many times here (atleast 6) with answers ranging from improper use of a variable to improper scope. However, I still cannot get clearInterval to stop my timer.
I will post the full code below - but I am looking to do something very simple. I am just trying to have code refresh an image (in mapbox) until another image is selected. The other image will load but the timer doesn't stop so it keeps refreshing the old image.
I set a global variable named "refreshtimerA" to hold the setInterval.
In addKEWX_REFLECTIVITY_toA(), this function runs the timer and refreshes an image in that window (it's a weather map) by use of a nested function called refreshKEWXL2REFLECTIVITY_A(). This works.
When the user activates the function addGOES_16_toA(), it should (as I added) activate clearInterval(refreshtimerA); But this does not stop it.
I have tried so many variations and sifted through here but I cannot find a working answer. I hope to clear this up as my whole project is completely stalled over something that should be simple. My code :
edit : link to dropbox complete html/js example: https://www.dropbox.com/s/11y2i859csj3o6k/stackoverflow.zip?dl=0
var refreshtimerA;
function clearAllPaneA() {
topleftmapbox.setLayoutProperty('overlay_KEWX_L2_REFLECTIVITY', 'visibility', 'none');
topleftmapbox.setLayoutProperty('overlay_GOES_16_CH02', 'visibility', 'none');
document.getElementById("reflectivityBar").style.visibility = "visible";
}
function addKEWX_REFLECTIVITY_toA(){
clearAllPaneA();
refreshtimerA = setInterval(refreshKEWXL2REFLECTIVITY_A, 5000); // 5 second constantly refreshes (works as the code is)
topleftmapbox.setLayoutProperty('overlay_KEWX_L2_REFLECTIVITY', 'visibility', 'visible');
document.getElementById("ReflectivityBar").style.visibility = "visible";
function refreshKEWXL2REFLECTIVITY_A() {
topleftmapbox.removeLayer('overlay_KEWX_L2_REFLECTIVITY');
topleftmapbox.removeSource('source_KEWX_L2_REFLECTIVITY');
topleftmapbox.addSource("source_KEWX_L2_REFLECTIVITY", {
"type": "image",
"url": "images/KEWX_L2_REFLECTIVITY.gif",
"coordinates": [
[-103.009641, 33.911],
[-94.009641, 33.911],
[-94.009641, 24.911],
[-103.009641, 24.911]
]
})
var layers = topleftmapbox.getStyle().layers;
// Find the index of the first symbol layer in the map style
var firstSymbolId;
for (var i = 0; i < layers.length; i++) {
if (layers[i].type === 'symbol') {
firstSymbolId = layers[i].id;
break;
}
}
topleftmapbox.addLayer({
"id": "overlay_KEWX_L2_REFLECTIVITY",
"source": "source_KEWX_L2_REFLECTIVITY",
"type": "raster",
"raster-opacity": 0.5,
"layout": {"visibility": "visible"},
}, firstSymbolId)
}
}
function addGOES_16_toA(){
clearInterval(refreshtimerA); // does not work
clearAllPaneA();
topleftmapbox.setLayoutProperty('overlay_GOES_16_CH02', 'visibility', 'visible');
}
addKEWX_REFLECTIVITY_toAis never called in your code - Aprillion