html5 - Javascript LocalStorage Scope -


i working localstorage first time , have ran scope issues.

when attempt console.log(test) undefined in second if statement. doing wrong?

my code follows;

$("document").ready(function(){      var is_stopped = false;      source.onmessage = function(event) {          if (is_stopped) {             localstorage.setitem('offline', event.data);             var test = localstorage.getitem('offline');             console.log(test); // works here         }                 if (!is_stopped) {             document.getelementbyid("result").innerhtml += "data:" + event.data + "<br>";             console.log(test); // undefined          }          $("#start").click(function(){             is_stopped = false;         });          $("#stop").click(function(){             is_stopped = true;         });  });  <div id="result"></div> <button id="stop"> stop</button> <button id="start"> start</button> 

its because is_stopped false, therefore doesnt enter first if , doesnt retrieves value. note variables declared inside function garbage collected when function ends.

var test;//stays persistent source.onmessage = function(event) {      if (is_stopped) {         localstorage.setitem('offline', event.data);         test = localstorage.getitem('offline');         console.log(test); // works here     }             if (!is_stopped) {         document.getelementbyid("result").innerhtml += "data:" + event.data + "<br>";         console.log(test);     } }; 

hint: moving click event listeners outside of other listener makes them work better...


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -