问题
Is there any tool (preferably extension/add-on to any browser) that allows you to see all the value changes of the desired JS variable in real time?
Previously I did something like this (in pure JS):
var someVariable;
var previousValueOfSomeVariable;
var f = function() {
if (previousValueOfSomeVariable != someVariable) {
console.log(Date.now(), someVariable);
previousValueOfSomeVariable = someVariable;
}
}
var TO = setInterval(f, 100);
It did the trick, but was, of course, inefficient (in reality the function was bigger, while it required object-copy function if variable was an object and further checks)...
UPDATE
I'm aware of console tools, but I'd like to see the history of changes, like:
someVariable
0ms: undefined
;
10ms: 5
;
40ms: 'someothervalue'
;
150ms: null
etc.
(Milliseconds are given for example purposes, not necessarily required). Maybe it can be done within the DevTools console, but I don't know how.
回答1:
The different DevTools (tested in Chrome DevTools, Firefox DevTools and Firebug) don't offer a way to see the value changes in real time. You always have to refresh their display manually.
Firefox offers an Object.prototype.watch() function (for other browsers there is a shim), which does what you want.
Example:
test = 0;
setInterval(() => test++, 1000);
window.watch("test", (id, oldValue, newValue) => {
console.log(new Date().toLocaleTimeString(), newValue);
return newValue;
});
This will output something like this:
09:51:03 1
09:51:04 2
09:51:05 3
09:51:06 4
09:51:07 5
Note: This function only allows to watch single properties of an object, so, in order to watch all object properties you need to loop over them and call watch()
for each one.
回答2:
Ah yes object.watch . It isn't used very often though! Here is a more detailed post of what I think you're looking for Listening for variable changes in JavaScript or jQuery
回答3:
Chrome dev tools has functionality for this.
insert the line
debugger;
right after the variable you're interested in. When your page executes and dev tools is open it will pause there and you can inspect the console.log with the value it had at that moment.
For example - say you have an onClick handler and want to see what information is passed in the event:
html:
<input onClicked={myFunc} />
JS
function myFunc(event){
console.log(event)
}
This will log the event to the console, but if you try to drill down chrome evaluates the obj when you click on it and since its long gone, its mostly null:
However if you use debugger, chrome pauses execution when it hits that and you can dig into the real event:
JS:
function myFunc(event){
console.log(event);
debugger;
}
Lets you drill down into the object as it was at the time you hit the debugger line
More info in the chrome dev tools site: https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints
来源:https://stackoverflow.com/questions/26353247/debugging-is-it-possible-to-see-value-of-js-variable-in-real-time