Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Js- How to restart setInterval after using clearInterval?

am using two simple buttons , one for scrolling and the other one for stoping the scroll,

the problem is :

when I reclick on the button of Scrolling after stop scrolling ,

the program crash suddenly, and gives me this error: Uncaught TypeError: Cannot set properties of null (setting 'src')

the names of imgs are 1 to 6 jpg for ex : firstphoto name is 1.jpg so I use cnt to crossover them in the code my code is :


  var setBallsMove;
  var cnt=1;
  var getParent=undefined;

document.write("\x3Cbutton onclick='sideShowing()' type='button'> SideShowing !\x3C/button>");
document.write("\x3Cbutton onclick='stop()' type='button'> stop !\x3C/button>");
document.write("\x3Cdiv    class='boy1' > \x3Cimg id=id"+cnt+"     src='SlideShow/1.jpg'  > \x3C/div>");

function sideShowing(){
   
        getParent = document.getElementById("id"+cnt); 
   
         window.setBallsMove=   setInterval(function slid (){     
                window.getParent.src="SlideShow/"+cnt+".jpg";
                getParent.id="id"+cnt;
                cnt++;
            if (cnt==6) {
            cnt=1;}}, 500);
}
function stop(){
 window.clearInterval(setBallsMove); 
 setBallsMove=undefined;
 getParent=undefined;

    };

I hope I wrote all info correctly ,thanks for your Pacience

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is not related to setInterval and clearInterval. You update the getParent.id with cnt then increment cnt. So the getParent.id and cnt are different next time when you try to getElementById and hence you get null. You should increment cnt before updating getParent.src and getParent.id.

window.setBallsMove = setInterval(function slid() {
    cnt++;
    if (cnt == 6) {
        cnt = 1;
    }
    window.getParent.src = "SlideShow/" + cnt + ".jpg";
    getParent.id = "id" + cnt;

}, 500);

But simply speaking, you just don't need to, and shouldn't, change the id at all. If you want to store information in an HTML element, use a custom data-* attribute.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!