1

I have created a setInterval function that scrolls onlimited times and two buttons start and end, I want when I click on start button the condition starts and when clicked on end the condition stops. Is there any way to do that? Here is my code:

pophtml:-

 <button class="input-btn start-button"><i class="fa fa-play" aria-hidden="true"></i> Start</button>
    <button class="input-btn scrap-button"><i class="fa fa-share-square" aria-hidden="true"></i> Export to csv</button>
     <button class="input-btn end-button"><i class="fa fa-stop" aria-hidden="true"></i> End</button>

popup js:-

   document.querySelector(".end-button").addEventListener("click", function () {
   chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {action: "end"});
    });
});

my content.js:-

 chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {

    var interval = '';
   if(request.action == 'start'){
    interval = setInterval(function(){
        $(document).scrollTop($(document).height());
              },1000);
        }

       else if(request.action == 'scrap')
       {
        alert('work in process');

       }
       else if(request.action == 'end')
       {
        clearInterval(interval);

       }
       else
       {
        alert('Wrong button placed')
       }
});

i tried it by using that previous method present but i am not getting which id to pass...

Rahul shukla
  • 378
  • 1
  • 12
  • i saw that tried doing with that but that is not working in mine – Rahul shukla Apr 04 '18 at 06:23
  • Please share that code that you've tried – Arnab Apr 04 '18 at 06:24
  • 1
    `setInterval` will return an id, to stop it use the id on `clearInterval(id);` – Eddie Apr 04 '18 at 06:25
  • @rahulshukla Create the variable before the `if`, otherwise the variable won't exist in the `else if`. `var interval; if (request.action == 'start') { interval = setInterval(...` – GG. Apr 04 '18 at 06:26
  • i tried by giving it the id too but the function inside my loop after start is for scroller that hits after every 10 seconds and i want it to stop when i click on end button i am adding the complete code please check – Rahul shukla Apr 04 '18 at 07:36

1 Answers1

0

Use clearInterval(intervalID) to clear interval.

var interval = '';
if (request.action == 'start') {
   interval = setInterval(function() {
        $(document).scrollTop($(document).height());
   },1000);
}
 else if (request.action == 'end'){
   // code to stop previous process
   clearInterval(interval);
}
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71