0

I want to show console log in html div. I am able to do that with below code.

var log = document.getElementById("logger")
 console.log = (function (method, log) {
        return function (text) {
            method(text);
            let msg = document.createElement('div');
            msg.textContent = text;
            log.appendChild(msg);
        };
 })(console.log.bind(console), log);

But console.log in functions does show in html div unless whole function execution is complete?

How can I show console logs in html div as function is executing (without waiting for function to complete its execution)?

In below example, I see logs in div after for loop execution gets complete.

function testfunction(){
    console.log('test function');
    for(let i=0; i<100000; i++){
        console.log(i);
    }
} 

I see updated logs in div in Inspect-> Elements and not on browser page.

enter image description here

10
  • 1
    I don't understand what you are asking. What do you mean by "as function is executing?" Commented Oct 19, 2021 at 17:12
  • function testfunction { console.log("1"); console.log("2"); someotherfunction(); } I want 1,2 to display in html div as soon it prints on console. with current code, html div shows 1,2 after testfunction execution gets complete. Commented Oct 19, 2021 at 17:19
  • Can you make an example that shows the problem you are having? I tested this and I see the log messages in both the console and the div. What is someotherfunction() doing? Commented Oct 19, 2021 at 17:27
  • 1
    In below example, I see logs in div after for loop execution gets complete. function testfunction(){ console.log('test function') for(let i=0;i<100000;i++){ console.log(i) } } Commented Oct 19, 2021 at 17:36
  • 1
    @RocketHazmat Is my question clear with for loop example ? Commented Oct 19, 2021 at 18:24

1 Answer 1

1

give it some time to execute otherwise everything will be processed at the same time

function testfunction(){
    console.log('test function');
    for(let i=0; i<100000; i++){
        setTimeout(() => {
           console.log(i);
        }, i * 5)
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.