debugging JS file - Client Side code

2019-09-01 04:50发布

Is there any easy way in which we can know the sequence in which methods are called in runtime?

Example: In my JS File, I have around 15 methods. There are some Asynchronous calls. With Async calls we never know the sequence in which they are called and executed. So : I want to know, if there is a way in which we can debug (using developer tools, IE\Chrome\FF) .. any tool which tells me which async call was called first and the order in which they are called.

Thanks.

3条回答
\"骚年 ilove
2楼-- · 2019-09-01 05:00

Using Chrome developer tools, you can use the Sources panel to debug javascript.

On the right side, you can add breakpoints for various types of events including XHR Breakpoints.

The execution will stop when the breakpoint is triggered and you can step through the execution flow.

I'm pretty sure Firefox and IE have similar tools.

查看更多
We Are One
3楼-- · 2019-09-01 05:04

Beside the given answers, you can also write a utility that will make wrap the methods of an object with logging:

It would be like this:

function addLogging(object) {   
    Object.keys(object).forEach(function (key) {
        if (typeof object[key] === 'function') {
            var originalFn = object[key];
            object[key] = function () {
                console.log('before calling', key);
                var result = originalFn.apply(this, arguments);
                console.log('after calling', key);
                return result;
            }
        }
    });
}

You can use lodash wrap method to help you.

Long ago I have answered a question regarding something similar like the above code: jQuery logger plugin

It didn't handle constructors perfectly, so it had problems like that. Here's the fixed resulting code.

You can also have a look at sinon.js, it provides spies and it can determine order of call of spied functions. But it might be a bit too much for just this, and it's might slow things down a little.

This method is a common thing done in aspect oriented programming. You can search about it and maybe try to use a AOP library. meld is a popular one.

Also instead of console.log in chrome you can use console.timeline, which gives you great visibility if used correctly.

查看更多
ら.Afraid
4楼-- · 2019-09-01 05:16

As ryan S suggested, using console.log can be a way of checking the sequence of code execution. So you can add console.log("1: [description]").

查看更多
登录 后发表回答