Home > database >  How do I replace the console message without it disappearing so fast?
How do I replace the console message without it disappearing so fast?

Time:11-01

I tried to make a stopwatch in the console, but the message kept on clearing before I had time to read it.
I tried increasing how long the Timeout function would go, but for some reason, it didn't make a difference.
Can somebody help me with making the messages not clear so fast?

setTimeout(function() {
  console.log("1");
}, 1000);
setTimeout(function() {
  console.clear()
},1099);
setTimeout(function() {
  console.log("2"); 
}, 2000);
setTimeout(function() {
  console.clear()
}, 2099);
setTimeout(function() {
  console.log("3");
}, 3000);
setTimeout(function() {
  console.clear()
}, 3099);

CodePudding user response:

second argument to settimeout represents time in milliseconds. 1000ms = 1seconds. consider this. Maybe you should increase the time it takes to run the console.clear(), base on your code it executes after 2 and 3 seconds.

CodePudding user response:

1- first line of code you tell your browser to execute that function which print on console number "1"

2- second line you tell browser after 99ms NOT 1099ms clear the console

Explain

second line won't clear your console after 1099ms! it will clear it after 99ms, because of all functions here work asynchronously, second setTimeout running(time is running) in behind, during execution first setTimeout

the trick here

the browser collect all Browser API functions and then execute it when Stack is empty which means when no codes after to execute it.

Summary setTimeout is asynchronous function, and all codes (in this example) will work asynchronously, not step by step, "the timer is one", all setTimeout executed together and they are running in behind(timer is running) and when timer is end, browser will execute "callback function" of that setTimeout

Resources : asynchronous concept

  • Related