3

I am building a chatsystem and i am using the AJAX technique for the asynchronous loading of a flat .txt file.

Next to the AJAX technique above, i also have a button that lets you manually start and stop the reloading of the flat .txt file.

When you start the reloading, it will do this every second/1000ms.

So far so good.. the problem comes when i want to clear the setInterval function with the clearInterval function. It works only once, and after i have restarted the loading of the document again through the start button, i can't stop it from reloading again with the other stop button.

I have tried almost every solution on stackoverflow regarding setInterval and clearInterval, but none of them seem to provide a solution or some of the threads are just left open without a solution. Is it even possible to stop and restart? and then stop again etc..

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("chatlog").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "chatlog.txt", true);
  xhttp.send();
}


function scrollWin(x,y) {
 
  window.scrollBy(x,y);

}

    var reload = setInterval(loadDoc,1000);


var myStartFunction = function () {

    var begin = setInterval(loadDoc,1000);
  
}

var myStopFunction = function() {

  var stop = clearInterval(reload);
}


var elmnt = document.getElementById("chatlog");

function scrollToTop() {
    elmnt.scrollIntoView(true); // Top
}


function scrollToBottom() {
    elmnt.scrollIntoView(false); // Bottom
}


var autoScroll = setInterval(function () {scrollToBottom()},3000);

function stopAutoScroll() {

    clearInterval(autoScroll);
}
BODY

{

 margin: 0;

}

.container-one

{

 width: 25%;

}

.buttons

{

 position: fixed;

 border-right: 1px solid #000000;

 height: 100%;

 z-index: 1;

 top: 0px;

 background-color: #7F7F7F;

}

.buttons UL

{

 list-style-type: none;

 margin: 0;

 padding: 0;

}

.buttons LI BUTTON

{

 width: 100%;

 display: block;

 border: 1px solid #020202;

 padding: 10px;

}

.firstbox

{

 margin-left: 240px;

 overflow: auto;

 margin-top: 115px;

 /*[disabled]border:1px solid #000000;*/

}

.chatheader H1

{

 text-align: center;

 padding: 20px;

 margin: 0 auto 0 9%;

 border-bottom: 5px solid #000000;

 position: fixed;

 background-color: #7C7C7C;

 top: 0px;

 width: 100%;

}

.firstbox P

{

 margin-left: auto;

 margin-right: auto;

 /*[disabled]border:0px solid #000000;*/

/*border-radius: 20px*/

 padding: 10%;

 background-color: #E0E0E0;

 width: 50%;

 /*[disabled]height:300px;*/

 /*[disabled]overflow:scroll;*/

 text-align: center;

}

#chatlog

{

 height: auto;

}
<!doctype html>

<html>

<head>

<link rel="stylesheet" type="text/css" href="chatstyle-reload.css">

<meta charset="utf-8" />

<!--<meta http-equiv="refresh" content="5" > -->

<title>Test page for requesting a webpage with the AJAX technique!</title>

</head>

<body>

<div class="container-one">

<div class="buttons">

<ul>

<li><button type="button" onclick="loadDoc()">Request the chatlog</button></li>
<li><button type="button" id="reloadBtn" onclick="myStartFunction()">Start updating the chatlog</button></li>
<li><button type="button" id="stopBtn" onclick="myStopFunction()">Stop reloading the chatlog</button></li>
<li><button type="button" onclick="document.getElementById('chatlog').innerHTML = 'Chatlog is hidden'">Hide chatlog</button></li>
<li><button type="button" onclick="scrollWin(0,-50)">Go to top of page</button></li>
<li><button type="button" onclick="scrollWin(0,200)">Go to bottom of page</button></li>
<li><button type="button" onclick="scrollToTop()">Scroll to the top of the element</button></li>
<li><button type="button" onclick="scrollToBottom()">Scroll to the bottom of the element</button></li>
<li><button type="button" onclick="stopAutoScroll()">Stop autoscroll</button></li>
<li><button type="button"> <a href="http://www.checkandtest.nl">Go back => to checkandtest.nl</a></button></li>

</ul>

</div>

</div>

<div class="chatheader">

<h1>Display the current chatlog in real-time</h1>

</div>


<div class="firstbox">

<p id="chatlog"></p>

</div>

<script src="functions.js"> </script>

</body>

</html>

1 Answers1

1

Your problem is here:

    var reload = setInterval(loadDoc,1000);


var myStartFunction = function () {

    var begin = setInterval(loadDoc,1000);

}

var myStopFunction = function() {

     var stop = clearInterval(reload);
}

You create an interal via setInterval and store it into reload, which can be correctly stopped, but when you start again via myStartFunction, you store it into a local unused variable called begin and at stop you intend to stop the interval having the id of reload, which was already stopped. Instead you will need to change myStartFunction as such:

var myStartFunction = function () {

    myStopFunction(); //Stop any previous unstopped interval
    reload = setInterval(loadDoc,1000);

}

EDIT

Here I elaborate the problem we had before the last edit on this answer. Before the last edit we had var reload = setInterval(loadDoc,1000); inside the myStartFunction, which creates a local variable called reload, but this local variable "shadows" the outer variable called reload, so, we were setting the value of the local variable and we expected the value to be assigned to the global variable. It was a typo on my part, but it's good to explain it. Let me give you an example:

var myVariable = 1;
function foo() {
    var myVariable = 2;
}
foo();
console.log(myVariable); //1

As you can see, we have two variables called myVariable. In the scope of the function we created a variable with the same name and assign a value of 2. Even though we call the function, the outer variable doesn't budge. Now, let's remove the var keyword inside the function:

var myVariable = 1;
function foo() {
    myVariable = 2;
}
foo();
console.log(myVariable); //2
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Thank you! i will try this out, i have been trying to solve this for a couple of days now. I hope this works, i will let you know if i run into issues. – Jhonattan Rapprecht Feb 11 '19 at 13:07
  • @JhonattanRapprecht you are welcome. If this answer solves your problem, then you might consider accepting it as the correct answer. – Lajos Arpad Feb 11 '19 at 13:19
  • I'm back.. but it is still not working. I can see that you are calling the myStopFunction from within the myStartFunction. The myStopFunction is not clearing any previous setInterval functions, it only clears it once. – Jhonattan Rapprecht Feb 11 '19 at 14:10
  • @JhonattanRapprecht how is it not working? Can you elaborate? – Lajos Arpad Feb 11 '19 at 16:29
  • I copied and pasted the code you wrote above. It is still behaving the same, i am not able to stop the setInterval function. Only when the page is loaded for the first time can i stop it. I don't know how to elaborate more.. it is a really simple thing i am trying to do with javascript. Thank you for your help anyway. – Jhonattan Rapprecht Feb 11 '19 at 17:45
  • 1
    @JhonattanRapprecht You can elaborate by telling me whether you get any errors. And you can create a JSFiddle. It is your interest to make the problem as understandable as possible and easier to reproduce as possible. And it is against your interest to call your own problem - which you are asking a question about - simple. If it was simple, we would not have this conversation. I am willing to help you and found a bug in your code. That does not mean you do not have other bugs. There might be a different problem as well. – Lajos Arpad Feb 11 '19 at 19:10
  • Yes.. I understand you are trying to help me, thank you. My apologies. This is the first real problem i have had since trying to build this app.. usually i find a solution in a couple of hours or days, but this is something different. I feel like i am missing a big lesson from Javascript here.. but i won't stop till i have figured it out. I think once i understand what is happening i will go the next level in my Javascript adventure. To come back to the issue, i was thinking it could be that i am invoking the 'myStopFunction' wrong? No errors are being logged in the console. – Jhonattan Rapprecht Feb 11 '19 at 20:35
  • 1
    @JhonattanRapprecht the problem you still had was that inside myStartFunction the reload variable was redefined via var reload = setInterval(loadDoc,1000); It was actually my typo, excuse me for that. Taking a look at the Fiddle I immediately realized what the problem is. This is the importance of having a reproducible example. Anyway, I updated my answer with this correction and also you can test the change in action here: https://jsfiddle.net/h0o6njwx/ – Lajos Arpad Feb 12 '19 at 11:36
  • Hi! Yes! you did it. You solved it. I agree it helps to be able to have a reproducible example, it also saves me a lot of time having to elaborate on all the steps i have taken to implement a solution. What was your typo? i did not even notice it.. and i still don't notice what was wrong. Was it really just a typo? Your answer solved my problem how can i mark your answer as a solution? Anyway thanks for all your help and for taking the time to teach me something, and also for your patience. – Jhonattan Rapprecht Feb 12 '19 at 13:39
  • @JhonattanRapprecht the typo was that I accidentally left the var keyword inside the function and we had var reload = setInterval(loadDoc,1000); instead of just reload = setInterval(loadDoc,1000); The difference is that the former creates a local variable called reload and assigns the value to it instead of assigning the value to the other variable in the outer scope. I will edit my answer to give you further explanation. If you intend to accept this answer, then you can click on the check mark to the left of the answer body. – Lajos Arpad Feb 13 '19 at 08:52
  • 1
    @JhonattanRapprecht I have added further explanation to the answer about my typo. – Lajos Arpad Feb 13 '19 at 08:59
  • I completely understand the issue now, no further explanation is needed. Thank you so much for explaining things. I hope this helps others with the 'setInterval' function in javascript. It is one of those functions that is used a lot for other things besides reloading documents, so i felt the need to thoroughly understand it now that i am beginning to learn, instead of having to learn later when i am already learning advanced topics. I accepted your answer as the solution. Have a great day and thanks again Lajos Arpad, take care. – Jhonattan Rapprecht Feb 13 '19 at 14:18