How do I replace the console message without it disappearing so fast? - javascript

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);

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.
#Mr.Buscuit, consider using the setInveral function,
let sec = 0;
setInterval(function () {
console.clear();
console.log(sec);
sec++;
}, 1000);
This log a new number to the log every second. Hope this helps.

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 (from beginning of timer) NOT 1099ms clear the console
Why 99ms? because All Timer API(Browser API) e.g (setTimeout, setInterval) works at same time, all of these functions that you do, they have a one(only one) timer, hence that means when timer reach at 1000ms, second setTimeout that you determined its timer with 1099ms reached at 1000ms as well (one timer), hence still 99ms remaining from 1099ms
Summary
Imagine there is one big timer is running for all functions, this means if we have 2 setTimeout with time we specified 1000ms (2 function with same time) this is not means after finish first function that need 1000ms, second starts setTimeout timer that will begin from scratch, hence need 1000ms again with total latency 2000ms, No, this is wrong, two functions will work together
very good resource for understand this concept : Async Concept

Related

Callback function not completed before setInterval's timeout

What would be the result if the callback function is not completed before the timeout of the setInterval function.
For example:
setInterval(function() {
// This block takes more than 5 seconds.
}, 4000);
Now the setInterval has a timemout of 4 seconds whereas the callback functions takes 5 seconds to complete. What would happend, would it wait for the function to complete or make execute the callback again in 4 seconds?
It will wait for the callback to complete, as JavaScript is single-threaded. If you run the below snippet, you will see that 'done' is printed every 5 seconds.
setInterval(function() {
let curr = new Date;
while(new Date() - curr <= 5000);
console.log('done');
}, 4000);
It depends.
If you put there some computations that happens to take 5 seconds (like looking for prime numbers or something), you'll lock the main thread and another call would be done only when it's unlocked, so in that case after about 5 seconds.
If the part that takes so long is for example a http request it will call the function every 4 seconds as it should. As far as I know there is no mechanism in setInterval that would check if function's promise is done or not.
So your setInterval has 2 parameters, a callback and the duration (4s)
There are a few things than can affect your interval:
your setInteval call a browser API which will start a timer to exactly 4 seconds. Once the timer triggers that 4 seconds, it will append your callback on the JS callback queue. Again, this happens exactly after 4s.
Once all the synchronous code will be executed, JS will start running the callbacks in the callback queue, one at a time.
To answer your question: if it's just the code that you posted, it will most likely take exactly 4 seconds. In case you have some heavy operation in your code that takes more than 4 seconds, that code may take longer since it will run only after.
Because of the event loop, the task queue and the single-threaded nature of JavaScript, it would always wait for the function to complete. Synchronous code is never canceled, unless the script is forcefully stopped.
The HTML standard says that timers must:
Wait until any invocations of [the timer initialization algorithm] that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.
Other timers and browser/runtime tasks would also run between the function. But if the function is running on the main thread, the program would only receive events while the function is not running. In a browser, this would mean that the website would not be interactive for most on the time.
For those reasons, such functions with heavy synchronous computations should be run inside a Worker or split among several tasks (see How to queue a task in JavaScript?).
(I'm assuming "This block takes more than 5 seconds." means that the function returns after 5 seconds.)
Check this out I found my own answer.
What this does is, it spawns a thread to execute the callback function after every timeout that works seperately.
document.write('Part 1:<br>');
setInterval(function() {
var x = Date.now();
document.write(x + '<br>');
setTimeout(function() {
var y = Date.now();
document.write(y.toString() + ' : ' + (y-x).toString() + '<br>');
}, 5000);
}, 2000);

Javascript Chrome console while

I was trying to create a loop in Chrome console with Javascript that executes the same function all the time. Instead it doesn't output anything and it actually just increases Chromes memory size until it crashes. Any advice on what's going wrong here?
while(true){
window.setTimeout(function (){
console.log("Hello");
}, 4000)}
You're creating an immense number of setTimeout events, all of which are created immediately in rapid succession and scheduled to be invoked 4000 ms after their creation.
Seems like you're looking for .setInterval() to perform a continuous invocation.
window.setInterval(function() {
console.log("Hello");
}, 4000);
To do it with setTimeout, you'd still not use any kind of imperative loop. You'd have the callback set up another setTimeout when it runs.
window.setTimeout(function f() {
console.log("Hello");
setTimeout(f, 4000);
}, 4000);
I gave the callback function the name f so that it could be used for the next timer.
In general, you don't "pause" your script. You schedule things to be done at a later time, and allow code to continue running until then. That's why you had a problem. The scheduled timer didn't pause anything, so the loop just keep running at full speed.

JavaScript Nested setInterval

I want to write nested timed code with setInterval. I tried the following but no response from browser (Chrome and FF) whatsoever:
setInterval(function() {
console.log('1');
setInterval(function(){
console.log('2');
},5000);
}, 2500);
I expected the above code will wait for two seconds and half before starting, and then log('1'), then wait for five seconds, and log('2'). What happened is that I got no response from both browsers (why?)
Second point, I replaced console.log with window.alert. I got response this time. But not the desired. The first response I get is after 2 seconds and half, second response is after five seconds, but then the two functions start to happen simultaneously.
So, what I want to achieve: Two blocks of code, two different time intervals, and no simultaneous occurrence of both blocks.
In your code an interval is created everytime the "outer" interval runs. In the example below the first interval will be created, and after a timeout of 2500ms the second one will be created.
setInterval(function(){
console.log('1');
}, 2500);
setTimeout(function(){
setInterval(function(){
console.log('2');
}, 5000);
}, 2500);
The behaviour is that your second setInterval is attached to context of the function of the first one.
So when the function of first setInterval end (is cleared), your second which was existing only in context of the function of first one disappear too
EDIT
You can use window.setInterval( /*...*/ ) instead of your second setInterval to make it persist but the behaviour will be that each 2,5 second you create an interval which each 5 second call console.log(2) so you'll get a number of Interval growing which is not what you're asking for.
You may want to use window.setTimeout( /*...*/ ) instead of your second setInterval. The behaviour will be the following :
1 (2.5sec)
1 (5 sec)
1 (7,5sec)
2 (7,5sec) //1st nested
1 (10sec)
2 (10sec) //2nd nested
...
if you want to call this both the operation only once, you are supposed to use setTimeout instead of setInterval.
Check below code:
setTimeout(function() {
console.log('1');
setTimeout(function(){
console.log('2');
},5000);
}, 2500);
this will log "1" after 2.5 sec and "2" after 7.5 sec (i.e. 2.5+ 5.0)
Try using this
var a=0;
setInterval(function() {
if(a==0){
one();
a++;
}
}, 2500);
setInterval(function() {
two();
a=0;
}, 5000);
function one() {
console.log('1');
}
function two() {
console.log('2');
}
Answring from mobile not able to put code in good manner...well use a variable to make run 2500 set interval once ..i am provinding you a bin link...well above code works

Is there any way to run a javascript function by a timer?

I have an app that gets data from a web service. I want to know that whether there is any way while the app is open but not being used to run a function every few minutes.
Basically, I want to check internet connectivity and check to make sure my web service is up.
You can use setInterval or use setTimeout.
setInterval works like a constant loop, so you can get a time for 3 seconds and every second it would run the code inside of the setInterval like so
setInterval(function()
{
alert("Hello");
}, 3000);
setTimeout works after a specific amount of time has gone by and then runs some code like so
setTimeout(function()
{
alert("Hello");
}, 3000);
The timer is in milliseconds so 1000 = 1 second
setInterval(function() {
alert("Will run every 5 seconds");
}, 5000);
setTimeout(function() {
alert("Will only run once after 5 seconds");
}, 5000);
Edit
As taxicala mentioned in the comments, the function will not be executed UNTIL 5 seconds has passed. If the thread is busy, it might be considerably longer than that. Most of the time it is a non-issue though, but worth having in mind.
Yes, you can use the setInterval function like:
var myVar = setInterval(function(){ yourKeepAliveFunction() }, 1000);
In the example above, yourKeepAliveFunction will run every second (1000 ms); myVar holds a handle to the timer, so once you want to stop running it, you can do so like:
clearInterval(myVar);

Putting a 10 second pause in xmlHttpRequest submit

This javascript code is fairly lengthy, but the most important part is the end where it posts:
httpwp['send'](paramswp);
I have tried without success to put a 10 second pause between each send. Normally it sends them all instantly.
full code http://pastebin.com/cEM7zksn
To delay 10 seconds before calling this, you could use setTimeout
setTimeout(function() { httpwp['send'](paramswp); }, 10000);
Or more simply:
setTimeout(function() { httpwp.send(paramswp); }, 10000);
The setTimeout() function does not pause execution for the specified time, it queues a function to be executed after the specified time. The line of code after setTimeout() will be executed immediately. So if you have the following code:
1 someFunction();
2 setTimeout(function(){console.log("From timeout");}, 10000);
3 console.log("After setTimeout()");
What will happen is on line 1 someFunction() will be called, then on line 2 an anonymous function will be queued to execute in 10 seconds time, then line 3 will execute, logging "After setTimeout()", and finally 10 seconds later the anonymous function will execute logging "From timeout".
If you want to code a loop where each iteration is spaced out by 10 seconds, rather than using a conventional for loop you write a function that uses setTimeout() to call itself:
// this for loop won't work
for(var i = 0; i < 20; i++) {
// do something
// pause for 10 seconds ---- can't be done
}
// so instead you do something like this:
function timeoutLoop(i, max) {
if (i < max) {
// do something
i++;
setTimeout(function(){timeoutLoop(i, max);}, 10000);
}
}
timeoutLoop(0, 20);
I found your code a little hard to read so I've not tried to integrate the above with it, but here is a really simple demo of the above working: http://jsfiddle.net/CrSEt/1/
Or here is a cleaner version that separates the actual processing from the loop function by using a callback: http://jsfiddle.net/CrSEt/
I'm sure if you play around a bit with the above you'll see how to get it to work in your code. You may want to consider setting subsequent timeouts from inside your ajax success callback.

Categories

Resources