{"id":2278,"date":"2022-02-08T17:37:13","date_gmt":"2022-02-08T16:37:13","guid":{"rendered":"https:\/\/ekiwi.de\/?p=2278"},"modified":"2022-02-08T17:37:13","modified_gmt":"2022-02-08T16:37:13","slug":"react-timer-setinterval-in-komponenten","status":"publish","type":"post","link":"https:\/\/ekiwi.de\/index.php\/2278\/react-timer-setinterval-in-komponenten\/","title":{"rendered":"React: Timer (setInterval) in Komponenten"},"content":{"rendered":"<p>Timer starten und stoppen in React-Komponenten.<\/p>\n<p><!--more--><\/p>\n<p>Ich hatte in einem Projekt Bedarf an einem Timer, welcher regelm\u00e4\u00dfig etwas aktualisiert. Dabei hatte ich ein kleines Problem, meine Beispielanwendung:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"\/wp-content\/uploads\/2022\/02\/timer_1.png\" alt=\"\" width=\"357\" height=\"222\" class=\"alignnone size-full wp-image-2279\" srcset=\"\/wp-content\/uploads\/2022\/02\/timer_1.png 357w, \/wp-content\/uploads\/2022\/02\/timer_1-300x187.png 300w\" sizes=\"auto, (max-width: 357px) 100vw, 357px\" \/><\/p>\n<p>Den Timer startete ich naiverweise einfach in der Komponente:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"\/wp-content\/uploads\/2022\/02\/timer_2.png\" alt=\"\" width=\"584\" height=\"553\" class=\"alignnone size-full wp-image-2280\" srcset=\"\/wp-content\/uploads\/2022\/02\/timer_2.png 584w, \/wp-content\/uploads\/2022\/02\/timer_2-300x284.png 300w\" sizes=\"auto, (max-width: 584px) 100vw, 584px\" \/><\/p>\n<p>React ist allerdings recht klug und l\u00e4dt und aktualisiert die Komponenten im Hintergrund, was bedeutete, dass dieser Code immer wieder ausgef\u00fchrt worden ist, wenn man zwischen den Tabs wechselt. In dessen Folge wurden immer wieder neue Timer-Events registriert.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"\/wp-content\/uploads\/2022\/02\/timer_3.png\" alt=\"\" width=\"437\" height=\"173\" class=\"alignnone size-full wp-image-2281\" srcset=\"\/wp-content\/uploads\/2022\/02\/timer_3.png 437w, \/wp-content\/uploads\/2022\/02\/timer_3-300x119.png 300w\" sizes=\"auto, (max-width: 437px) 100vw, 437px\" \/><\/p>\n<p>Meine L\u00f6sung war die Komponente in eine React-Komponente umzubauen. Diese bringt dann Dinge wie &#8222;componentDidMount()&#8220; und &#8222;componentWillUnmount()&#8220; mit. Diese Events werden ausgef\u00fchrt, wenn die Komponente angezeigt wird und auch, wenn diese wieder verschwindet. <\/p>\n<pre>\r\nimport * as React from 'react';\r\n \r\nclass Clock extends React.Component&lt;any, any&gt; {\r\n    private timerId: any;\r\n \r\n    constructor(props: any) {\r\n        super(props);\r\n        this.state = {  currentTime : &quot;-&quot; };\r\n    }\r\n \r\n    componentDidMount() {\r\n        console.log(&quot;Starting timer 1&quot;);\r\n        this.timerId = setInterval(this.updateStatus, 1000);\r\n    }\r\n \r\n    componentWillUnmount() {\r\n        console.log(&quot;Stopping timer 2&quot;);\r\n        clearInterval(this.timerId);\r\n    }\r\n \r\n    updateStatus = () =&gt; {\r\n        console.log(&quot;Timer 1 fired&quot;);\r\n        let currentdate = new Date();\r\n        let datetime = &quot;Last Sync: &quot; + currentdate.getDate() + &quot;\/&quot;\r\n            + (currentdate.getMonth()+1)  + &quot;\/&quot;\r\n            + currentdate.getFullYear() + &quot; @ &quot;\r\n            + currentdate.getHours() + &quot;:&quot;\r\n            + currentdate.getMinutes() + &quot;:&quot;\r\n            + currentdate.getSeconds();\r\n \r\n        this.setState({ currentTime: datetime});\r\n    }\r\n \r\n    render() {\r\n        return &lt;div&gt;\r\n            &lt;p&gt;{this.state.currentTime}&lt;\/p&gt;\r\n        &lt;\/div&gt;\r\n    };\r\n}\r\n \r\nexport default Clock;\r\n<\/pre>\n<p>Dies erlaubt es, die Referenz auf den Timer, die ID, zu speichern und den Timer beim Ausblenden mit &#8222;clearInterval&#8220; wieder zu entfernen.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"\/wp-content\/uploads\/2022\/02\/timer_4.png\" alt=\"\" width=\"523\" height=\"309\" class=\"alignnone size-full wp-image-2282\" srcset=\"\/wp-content\/uploads\/2022\/02\/timer_4.png 523w, \/wp-content\/uploads\/2022\/02\/timer_4-300x177.png 300w\" sizes=\"auto, (max-width: 523px) 100vw, 523px\" \/><\/p>\n<p>Fertig! Der Timer wird nun gestartet und wieder gestoppt, sodass dieser nur einmal aktiv ist.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"\/wp-content\/uploads\/2022\/02\/timer_5.png\" alt=\"\" width=\"272\" height=\"139\" class=\"alignnone size-full wp-image-2283\" \/><\/p>\n<p>Den Beispielcode des Projekts <a href=\"https:\/\/github.com\/andydunkel\/react_examples\/tree\/main\/timer\" target=\"_blank\" rel=\"noopener\">gibt es auf Github<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>Timer starten und stoppen in React-Komponenten.<\/p>\n","protected":false},"author":1,"featured_media":2260,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_links_to":"","_links_to_target":""},"categories":[15],"tags":[44,561],"class_list":["post-2278","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-javascript","tag-react"],"_links":{"self":[{"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/posts\/2278","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/comments?post=2278"}],"version-history":[{"count":0,"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/posts\/2278\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/media\/2260"}],"wp:attachment":[{"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/media?parent=2278"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/categories?post=2278"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ekiwi.de\/index.php\/wp-json\/wp\/v2\/tags?post=2278"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}