How to stop js setInterval when DOM is removed in Vuejs 3?

I have a component.vue file which houses an SVG. The animations for the SVG are defined inside the tags of the file. The script code modifies the behavior of the different parts of SVG.

The problem is when the DOM is re-rendered (when I go to another router-link/Page). I start getting

Uncaught ReferenceError: <SVG's part id> is not defined

in the console. The animation code has setInterval usage. So there are infinite instances of error – unless I refresh the browser or move back to the page (which has the SVG DOM).

export default {
  name: "JackHammer",

  mounted() {
    var funcs = [
      "load",
      "addEventListener",
      "daysLeft",
      "getElementById",
      "setInterval",
      "getTime",
      "getTimezoneOffset",
      "floor",
      "textContent",
    ];

    var daysLeft;
    var frameNumber = 0;
    var endDate = new Date(2021, 1, 20, 10, 0, 0, 0);

    window.addEventListener(
      "load",
      function () {
        initJackhammer();
      },
      false
    );
    function initJackhammer() {
      daysLeft = document.getElementById(funcs[2]);
      ShowTimeLeft();
      window.setInterval(ShowTimeLeft, 1000);

      var jackhammerTip = document.getElementById("jackhammerTip");
      var jackhammer = document.getElementById("jackhammer");
      var jackBody = document.getElementById("jackBody");
      var jackArms = document.getElementById("jackArms");
      setInterval(animateJackhammer, 40);
    }

    function ShowTimeLeft() {
      // if (!document.getElementById("hoursLeft")) {
      //   return;
      // }
      var CurrTime = new Date();
      var timeDiff = (endDate - CurrTime) / 1000;
      var timeDiffInDays = Math.floor(timeDiff / 86400);
      timeDiff -= timeDiffInDays * 86400;
      var TimeDiffHours = Math.floor(timeDiff / 3600) % 24;
      timeDiff -= TimeDiffHours * 3600;
      var TimeDiffMinutes = Math.floor(timeDiff / 60) % 60;
      timeDiff -= TimeDiffMinutes * 60;
      var TimeDiffSeconds = Math.floor(timeDiff % 60);
      daysLeft.textContent = timeDiffInDays;
      hoursLeft.textContent = TimeDiffHours;
      minutesLeft.textContent = TimeDiffMinutes;
      secondsLeft.textContent = TimeDiffSeconds;
    }

    function animateJackhammer() {
      // console.log(jackhammerTip)
      if (!document.getElementById("jackhammerTip")) {
        return;
      }

      frameNumber++;
      jackhammerTip.setAttribute(
        "transform",
        "translate(0," + (frameNumber % 3) * -3 + ")"
      );

      jackhammer.setAttribute(
        "transform",
        "translate(0," + -Math.sin(frameNumber * 1.5) + ")"
      );

      var jackBodyAmount = Math.sin(frameNumber) + 2;
      jackBody.setAttribute(
        "transform",
        "translate(0," + -jackBodyAmount + ")"
      );
      jackArms.setAttribute(
        "transform",
        "translate(0," + -jackBodyAmount + ")"
      );

      if (frameNumber == 1000) frameNumber = 0;
    }
  },
};

I am new to Vuejs and JS as a whole.
I want to JS code to suspend when the DOM is removed and again start when its rendered again. What can be the most optimized way to achieve this?

Currently, I am just exiting out of the functions if the DOM element does not exist. Would appreciate a better approach.

416 thoughts on “How to stop js setInterval when DOM is removed in Vuejs 3?”

  1. Hello I am so delighted I found your website, I really
    found you by mistake, while I was researching on Google for
    something else, Nonetheless I am here now and would just
    like to say kudos for a fantastic post and a all round exciting blog (I also love the theme/design),
    I don’t have time to look over it all at the minute but I have saved it and also added your RSS feeds, so when I
    have time I will be back to read much more, Please do keep up the excellent job.

    Reply
  2. I really like your blog.. very nice colors & theme. Did you make
    this website yourself or did you hire someone to do it for you?

    Plz reply as I’m looking to create my own blog and would like to know where u got this from.
    thanks

    Reply
  3. I’m impressed, I have to admit. Seldom do I encounter a blog that’s both equally educative
    and engaging, and without a doubt, you’ve hit the nail on the head.

    The problem is something that too few folks are speaking intelligently about.
    I am very happy that I came across this during my hunt for
    something regarding this.

    My website; Kodo Detox Patch

    Reply
  4. I’ve been surfing on-line greater than three hours nowadays, yet I by no means found any interesting
    article like yours. It is pretty price sufficient for me.
    In my view, if all webmasters and bloggers made just right
    content material as you did, the net will likely be much more
    helpful than ever before.

    My homepage :: Gorges Cream Reviews

    Reply
  5. You could definitely see your enthusiasm in the
    paintings you write. The arena hopes for more passionate writers such as you who aren’t
    afraid to mention how they believe. At all times
    go after your heart.

    my page … Viking XL

    Reply
  6. It’s a pity you don’t have a donate button! I’d without a doubt donate to this superb blog!
    I guess for now i’ll settle for book-marking and adding your RSS feed to my
    Google account. I look forward to brand new updates and will talk about this
    blog with my Facebook group. Chat soon!

    Here is my homepage Cognifen Ingredients

    Reply
  7. I really love your blog.. Excellent colors & theme. Did you create this site
    yourself? Please reply back as I’m looking
    to create my own site and would like to learn where you got this
    from or just what the theme is named. Thanks!

    Here is my page; Dick Fuel

    Reply
  8. Thanks for your entire work on this site. Gloria loves conducting
    investigations and it’s really easy to understand why.
    My spouse and i know all concerning the dynamic method
    you give very helpful thoughts through this website and as well
    as cause response from other individuals on this article then our favorite simple princess is truly understanding a
    lot. Take advantage of the rest of the new year.
    You are always performing a superb job.

    My web page Sage Elixir

    Reply
  9. Can I simply say what a relief to discover somebody that genuinely
    knows what they’re talking about on the web.
    You certainly know how to bring a problem to light and make
    it important. More and more people must read this and understand this
    side of the story. It’s surprising you’re not more popular since you certainly have the gift.

    Feel free to surf to my site … http://www.alisteqama.net

    Reply
  10. Please let me know if you’re looking for a article writer for your blog.
    You have some really great posts and I think I would be a good
    asset. If you ever want to take some of the load off,
    I’d love to write some content for your blog in exchange for a link back
    to mine. Please blast me an email if interested. Thank you!

    Reply
  11. I just couldn’t depart your web site prior to suggesting that I really enjoyed the usual information a person provide to your guests?
    Is gonna be back steadily to investigate cross-check new posts

    Look at my blog … xe88 game apk (918kiss-m.com)

    Reply
  12. I don’t drop a bunch of responses, but i did some searching and wound
    up here How to stop js setInterval when DOM is removed in Vuejs 3?
    – JavaScript Help. And I actually do have a few questions for you
    if it’s allright. Is it just me or does it look like a few of these
    comments look like coming from brain dead folks? 😛 And,
    if you are writing at additional social sites, I would like to keep up with everything fresh you have to post.
    Would you make a list of the complete urls of
    all your community pages like your linkedin profile, Facebook
    page or twitter feed?

    Feel free to visit my web page – Nitro Strive Nitric Oxide

    Reply
  13. Hi, all the time i used to check blog posts here early in the morning, for the reason that i love to learn more and
    more.

    Also visit my homepage :: 3win8 android – Aidan,

    Reply
  14. Good day! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in exchanging links or maybe
    guest writing a blog article or vice-versa? My blog goes
    over a lot of the same subjects as yours and I think we could greatly
    benefit from each other. If you might be interested feel free to send me an email.
    I look forward to hearing from you! Superb blog by the
    way!

    my web site 918kiss plus apk ios download

    Reply
  15. Please let me know if you’re looking for a author for your site.

    You have some really good articles and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d really like to write some material
    for your blog in exchange for a link back to mine.
    Please shoot me an e-mail if interested. Thanks!

    Reply
  16. It’s appropriate time to make some plans for the future and it’s time to be happy.
    I’ve read this post and if I could I wish to suggest you few interesting things or advice.
    Perhaps you could write next articles referring to this article.

    I wish to read more things about it!

    Here is my blog post; http://marchegabonais.com/index.php/blog/85030/boosting-the-feminine-libido-herbs-to-boost-your-sexual-drive/

    Reply
  17. Hey there! I understand this is somewhat off-topic but I needed to ask.
    Does managing a well-established blog like yours require a massive amount work?
    I’m brand new to running a blog however I do write in my diary on a daily basis.
    I’d like to start a blog so I can share my personal experience and feelings
    online. Please let me know if you have any kind of suggestions
    or tips for new aspiring bloggers. Appreciate
    it!

    Here is my blog; http://web.jmjh.tn.edu.tw/

    Reply
  18. I’ve been browsing on-line greater than three hours nowadays,
    but I never found any attention-grabbing article like yours.
    It’s lovely worth enough for me. In my opinion, if all website owners and bloggers
    made excellent content as you probably did, the
    web will probably be a lot more helpful than ever before.

    Here is my website: Gorges Cream Review

    Reply
  19. Greate article. Keep posting such kind of info on your blog.
    Im really impressed by it.[X-N-E-W-L-I-N-S-P-I-N-X]Hey there, You’ve performed a
    great job. I will certainly digg it and for my part recommend to my friends.

    I am confident they will be benefited from this site.

    my webpage; http://www.hltkd.tw/

    Reply
  20. Hmm it looks like your site ate my first comment (it was super long) so
    I guess I’ll just sum it up what I had written and say,
    I’m thoroughly enjoying your blog. I as well am an aspiring
    blog writer but I’m still new to the whole thing.
    Do you have any helpful hints for novice blog writers? I’d
    certainly appreciate it.

    Also visit my site … Slimingo Reviews

    Reply
  21. Good day! I could have sworn I?ve visited this site before but after
    browsing through some of the articles I realized it?s new to me.
    Nonetheless, I?m certainly delighted I discovered it and I?ll be bookmarking it
    and checking back often!

    Review my web page Alpha Extracts

    Reply
  22. Thank you for sharing superb informations. Your web site is very cool.
    I am impressed by the details that you have on this site.

    It reveals how nicely you understand this subject. Bookmarked
    this web page, will come back for more articles. You, my friend, ROCK!
    I found simply the information I already searched all over the place and
    simply could not come across. What a great site.

    My blog KetoRedux

    Reply
  23. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire in fact enjoyed account
    your blog posts. Anyway I will be subscribing to your augment and even I achievement you access consistently quickly.

    My website: Drone Max V2

    Reply
  24. I am really loving the theme/design of your
    website. Do you ever run into any browser compatibility problems?
    A number of my blog audience have complained about my site
    not working correctly in Explorer but looks great in Safari.
    Do you have any recommendations to help fix this issue?

    my site; dosurveys4cash.co.za

    Reply
  25. hey there and thank you for your information – I have certainly picked up something new from right here.

    I did however expertise a few technical points using
    this site, since I experienced to reload the web site lots
    of times previous to I could get it to load correctly. I had been wondering if
    your hosting is OK? Not that I’m complaining, but sluggish loading instances times will often affect your placement in google and can damage your high-quality score if ads
    and marketing with Adwords. Anyway I am adding this RSS to my email
    and could look out for a lot more of your respective intriguing content.
    Make sure you update this again soon..

    My blog post – Clark

    Reply
  26. Pingback: whats keto
  27. I simply wanted to develop a quick message to be able to thank you
    for those magnificent strategies you are posting here.
    My prolonged internet research has now been compensated
    with beneficial information to share with my companions.
    I would assume that many of us visitors are very fortunate to be in a really good site with so many perfect professionals with insightful
    methods. I feel quite blessed to have encountered your
    entire webpages and look forward to plenty of more brilliant moments reading
    here. Thanks a lot again for a lot of things.

    Also visit my webpage True Keto Review

    Reply
  28. Oh my goodness! Amazing article dude! Thank you, However I am having troubles with your
    RSS. I don?t know why I cannot join it. Is there anybody else having the same RSS issues?
    Anyone who knows the answer will you kindly respond?

    Thanks!!

    My web site :: Maximum Recall

    Reply
  29. I really wanted to write down a small word to be able to appreciate you for all of the awesome steps you are
    showing at this website. My considerable internet lookup has
    at the end of the day been honored with pleasant facts and strategies to write about with my classmates and friends.
    I would assume that we website visitors actually are really lucky to
    dwell in a remarkable website with very many lovely professionals with useful tactics.
    I feel pretty grateful to have discovered your entire webpages
    and look forward to really more cool times reading here.
    Thanks again for everything.

    Here is my website – http://aixindashi.org/out/387675

    Reply
  30. Pingback: stromectol goodrx
  31. You actually make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand.
    It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the hang of it!

    Reply
  32. I think what you said was very reasonable. But, think on this, what if you added a little content?
    I mean, I don’t want to tell you how to run your blog, but what if you added a headline to possibly grab a
    person’s attention? I mean How to stop js setInterval when DOM
    is removed in Vuejs 3? – JavaScript Help is a little vanilla.
    You could look at Yahoo’s home page and note how they create
    news headlines to get viewers to open the links. You might add
    a video or a related picture or two to grab readers excited about what you’ve
    written. In my opinion, it would make your
    website a little livelier.

    Also visit my page – Oracle Leaf CBD

    Reply
  33. I was just looking for this information for a while.
    After six hours of continuous Googleing, at last I got it in your website.
    I wonder what is the lack of Google strategy that don’t rank this type of informative websites in top of the list.

    Generally the top websites are full of garbage.

    Feel free to surf to my web-site … ToxyBurn

    Reply
  34. Do you mind if I quote a few of your posts as long
    as I provide credit and sources back to your website? My blog is in the
    very same niche as yours and my users would really benefit from some of the information you present here.
    Please let me know if this ok with you. Thanks!

    Reply
  35. Hello there! This article couldn’t be written much better!
    Looking through this article reminds me of my previous
    roommate! He continually kept talking about
    this. I most certainly will forward this article to
    him. Fairly certain he will have a great read.
    I appreciate you for sharing!

    my web site – Reneaux Serum

    Reply
  36. Hello there! I could have sworn I’ve been to this blog before but after looking at many
    of the articles I realized it’s new to me. Anyhow, I’m
    certainly happy I found it and I’ll be bookmarking it and
    checking back often!

    Reply
  37. First of all I would like to say excellent blog! I had a quick question that I’d like to ask if you do not mind.
    I was curious to find out how you center yourself and clear your
    thoughts prior to writing. I’ve had trouble clearing my thoughts in getting my thoughts out
    there. I truly do take pleasure in writing however it
    just seems like the first 10 to 15 minutes are wasted simply just trying to figure out how
    to begin. Any ideas or hints? Many thanks!

    Have a look at my homepage; Vialis Health Male Enhancement

    Reply
  38. Hey there this is kind of of off topic but I was wondering if blogs
    use WYSIWYG editors or if you have to manually
    code with HTML. I’m starting a blog soon but have no coding
    knowledge so I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

    My blog – Derma Ella

    Reply
  39. Thanks on your marvelous posting! I really enjoyed reading it, you can be a great author.
    I will always bookmark your blog and definitely will come back someday.
    I want to encourage you to continue your great job, have a nice
    holiday weekend!

    Reply
  40. It’s appropriate time to make some plans for the future and it’s time
    to be happy. I’ve read this post and if I could I wish to suggest you
    few interesting things or tips. Perhaps you can write next
    articles referring to this article. I want to read more
    things about it!

    Check out my webpage; novogorskpark.ru

    Reply
  41. Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get
    my blog to rank for some targeted keywords but I’m not seeing very good gains.

    If you know of any please share. Many thanks!

    Here is my webpage – Cogni360 Pills

    Reply
  42. Appreciating the persistence you put into your blog and
    in depth information you provide. It’s great to come across a blog every once in a while
    that isn’t the same unwanted rehashed material. Fantastic read!
    I’ve saved your site and I’m adding your RSS feeds to my Google
    account. scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

    Reply
  43. This is a very good tip particularly to those fresh to
    the blogosphere. Short but very accurate information? Appreciate
    your sharing this one. A must read article!

    Here is my web page: Eric

    Reply
  44. Howdy just wanted to give you a quick heads up. The words in your content seem to be running off the
    screen in Opera. I’m not sure if this is a format issue or something to do
    with browser compatibility but I thought I’d post to let you
    know. The style and design look great though!
    Hope you get the problem solved soon. Thanks

    Also visit my page … ToxyBurn Reviews

    Reply
  45. Pingback: cap stromectol 6
  46. First off I want to say superb blog! I had a quick question in which I’d
    like to ask if you don’t mind. I was curious to know
    how you center yourself and clear your head before writing.
    I’ve had a tough time clearing my thoughts in getting my ideas out
    there. I do take pleasure in writing but it just seems like the first
    10 to 15 minutes are generally wasted just trying to figure
    out how to begin. Any recommendations or hints?
    Many thanks!

    Look into my site … prettypeople.club

    Reply
  47. Hey! I know this is somewhat off-topic but I needed to ask.
    Does managing a well-established blog like yours take a lot of work?
    I am completely new to blogging however I do write in my diary daily.
    I’d like to start a blog so I can easily share my experience and views online.
    Please let me know if you have any ideas or tips for brand
    new aspiring blog owners. Thankyou! http://ciaalis2u.com/

    Reply
  48. Pingback: ivermectin 3
  49. Good day I am so delighted I found your website, I really found you by accident, while
    I was researching on Google for something else, Anyhow I am here
    now and would just like to say cheers for a tremendous post and a all round exciting blog (I also love the theme/design), I don’t
    have time to read through it all at the minute
    but I have saved it and also added in your RSS feeds, so when I have time I will
    be back to read more, Please do keep up the awesome work. http://harmonyhomesltd.com/Ivermectinum-during-pregnancy.html

    Reply
  50. Howdy! I could have sworn I?ve visited this web site before but after browsing through a few of the posts
    I realized it?s new to me. Anyhow, I?m certainly happy I discovered it and I?ll
    be bookmarking it and checking back often!

    Review my web page :: favourite asmr

    Reply
  51. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment.
    Is there any way you can remove people from that service? Bless you!

    Reply

Leave a Comment