Is there a javascript event to variable change? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Is there a javascript event to variable change?

for example: var a = 2; event(.........) { //code to execute when a becomes 4 } I know I can check for its value in a loop but that is too CPU heavy and I have some other simultanious tasks too.

16th Jul 2020, 3:52 AM
Gyan Prakash Singh Jaruhar
Gyan Prakash Singh Jaruhar - avatar
7 Answers
+ 3
Gyan Prakash Singh Jaruhar if the receiving elements do not want to monitor data change, then the responsibility fall on updating element. You can use custom event method, define the custom event name with binding data, set Event Listener on all the receiving elements. Then on the updating part, whenever data is updated, it dispatches the custom event to inform all receiving elements. https://code.sololearn.com/WsSwaQxvZPxp/?ref=app
16th Jul 2020, 7:15 AM
Calviղ
Calviղ - avatar
+ 5
Well, you could always make 2 variable with the same value, then make a function that checks if the 2 variables are equal, then setInterval that function so it keeps on checking over and over until they are not equal to each other, then perhaps clear the interval Like.. var main_variable=20; var checking_variable=20; function check(x,y,IntervalName) { if(x==y) { //Does nothing } else { //Code to be executed if they are no longer the same clearInterval(IntervalName) } } var checker = setInterval(check(main_variable,checking_variable,checker)100); Hope this solved your problem!
16th Jul 2020, 11:54 AM
Vachila64☕
Vachila64☕ - avatar
+ 3
Please be more descriptive. There are many events in JS, can you say which one you want to intercept? You want to change a variable value when the event fires right? just to be sure ...
16th Jul 2020, 4:03 AM
Ipang
+ 3
Ah so it's the other way around ... Not too sure whether there is any event that watches for variable value changes. Maybe you can make a class (which contains the value as a member), then make a setter method to change the value. You then can call a method in that setter, or just do something as the setter does its work. Look forwards to others' valuable suggestions.
16th Jul 2020, 4:20 AM
Ipang
+ 3
Then just put the setInterval outside the loop, it will still run😉. If you could show the code, it would be much easier to give specific pointers and help, but if you can't, that's fine as well🙂
16th Jul 2020, 11:59 AM
Vachila64☕
Vachila64☕ - avatar
+ 2
Ipang I want to fire a event when a variable change to specific value
16th Jul 2020, 4:07 AM
Gyan Prakash Singh Jaruhar
Gyan Prakash Singh Jaruhar - avatar
+ 1
Vachila64 I have some simultanious tasks too! And throwing the setInterval will put it in a loop preventing other executions
16th Jul 2020, 11:56 AM
Gyan Prakash Singh Jaruhar
Gyan Prakash Singh Jaruhar - avatar