Westlenando
Westlenando

Reputation: 88

Is there a way to constantly update a variable?

I'm trying to make this thing where in one tab you type something, and in another it pops up. However, I have to constantly reload the page to get my next message. First, this is what I tried.

<!DOCTYPE html>
<html>
<body>
    <p id="message"></p>
    <script>
        var x = localStorage.getItem('message')
        var i;
        for (i = 0; i < 5) {
            document.getElementById('message').innerHTML = x;
        }
    </script>
</body>
</html>

HOWEVER, this puts the page in a constant reloading state. How would I do this? Thanks!

Upvotes: 0

Views: 4954

Answers (3)

javascwipt
javascwipt

Reputation: 1178

You have an infinite loop. A for loop has four steps.

  • Initialization: Declaring the variable and its initial value(Happens once)
  • Condition: Checking the condition to continue the loop
  • Final
  • Expression: Usually where you handle your logic that will end your loop like incrementing the i variable
  • Execution: Execute the code in the code block

Your method is working but it never stops working, hence why your browser doesn't stop loading.

The for loop moves too quickly anyway and it would be better to put to listen for a storage event update on your document.

var messageContainer = document.querySelector('#message')

window.addEventListener('storage', function() {
var text = localStorage.getItem('message')
messageContainer.textContent = text
}

Upvotes: 2

blex
blex

Reputation: 25634

Instead of constantly polling for updates, you can set up an event listenener to catch every message that is sent. You can do this thanks to the storage event:

// Every time a change it made to this domain's localStorage (item added, changed, removed)
window.addEventListener('storage', function() {
  // Update your DOM 
  document.getElementById('message').innerHTML = localStorage.getItem('message');     
});

Upvotes: 2

Barmar
Barmar

Reputation: 781088

Use setInterval instead of a loop.

setInterval(function() {
    var x = localStorage.getItem('message');
    document.getElementById('message').innerHTML = x;
}, 1000);

This will update every second.

Upvotes: 4

Related Questions