DEV Community

Cover image for How to make a Variable Observer
Mafee7
Mafee7

Posted on

How to make a Variable Observer

There are many Deprecated Methods to listen for changes in a variable's value in Javascript

Here is a easy way to listen for changes in a variable's value:

var Var = window.innerWidth + ", " + window.innerHeight; // Can Put Anything Here as The Value.
var oldVar = Var; // Set oldVar to Var.

setInterval(function(){
    // Set Var to Value;
    Var = window.innerWidth + ", " + window.innerHeight; 
},100)

setInterval(function(){
    if(oldVar !== Var){ // Check If Var Not = oldVar.
        // Do Something.
        console.log("Window Resized!");
        oldVar = Var; // Set oldVar to Var to reset the code.
    }
}, 100);

Enter fullscreen mode Exit fullscreen mode

Or Directly Use Value:

var oldVal;


setInterval(function(){
    if(oldVar !== window.innerHeight){ // Check If Valuez Not = oldVar.
        // Do Something.
        console.log("Window Resized!");
        oldVar = window.innerHeight; // Set oldVar to Value to reset the code.
    }
}, 100);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)