I need to generate an infinite loop that ends when the user clicks on the page to stop the loop.
Is this possible to do?
The idea is that when I receive a notification from a user, the browser notifies me (at the top of the browser).
socket.on('receivedMessage' , function (msg){
document.title = "Tienes mensajes nuevos";
});
So I want to make the title "blink", putting the message: "You have new messages" and after X seconds, "page name", and after X seconds, "You have new messages".
I had thought to implement it withsetTimeout
var titleNotificacion;
alertFunc();
function alertFunc() {
titleNotificacion = setTimeout(function() {
document.title = "Tienes mensajes nuevos";
alertFunc2();
}, 2000);
}
function alertFunc2() {
titleNotificacion = setTimeout(function() {
document.title = "Nombre-de-la-pagina";
alertFunc();
}, 2000);
}
This does it for me correctly! The message blinks!!, but when I enter the page, or when I focus on it, it never stops setTimeout
, because I have made a function loop.
Then, I have been thinking, and it was more worthwhile to make an infinite loop with these two messages, calling the functions setTimeout
and saying to stop the execution of the loop, when the user does a window.click
.
New code modified after the last contributions
socket.on('receivedMessage' , function (msg){
window.DoInfiniteLoop = true;
InfiniteLoop();
function InfiniteLoop() {
if( window.DoInfiniteLoop === true)
setTimeout(function() {
document.title = "nombre-pagina";
document.onclick = function() {
document.title = "nombre-pagina"; window.DoInfiniteLoop = false;
InfiniteLoop();
}
}, 1000);
setTimeout(function() {
document.title = "Tienes mensajes nuevos";
document.onclick = function() {
document.title = "nombre-pagina"; window.DoInfiniteLoop = false;
InfiniteLoop();
}
}, 2000);
setTimeout( InfiniteLoop, 3000 );
}
});
It makes me "blink" correctly. But when I click on the browser, it doesn't stop the loop!, at the moment of clicking, if you mind me, but then it continues with the course of the loop.
Javascript uses a single thread for its execution, so if you do a rough infinite loop , type:
will leave the browser frozen . Possible pending events will accumulate in the event queue, without anyone processing them.
It is necessary to let him breathe , so that he can process the glue. A simple way to do it is:
With this, what we do is continuously add an event to the queue, which will be processed when its turn comes. Notice that we always exit the function
InfiniteLoop( )
. It is in these outputs that the browser processes the event queue.To start the loop:
And, when you want to stop it, you just have to do:
You can do this from any event handler you have enabled.
More information about the concurrency model and event loop .
EDIT
The following code will change the title. I haven't tested it , but with minor modifications it should work.
You can try this from an English question and change it to whatever you need
the question in english
The code itself: