Part of GDPR means respecting a users right to privacy (which should be respected anyway regardless of any, this includes the right not to be tracked.
After looking this up I'm surprised at the amount of tracking services in the public domain that completely ignore this; including social media tracking and advertisers. Monsanto (Piwik) is one of the only services I've found to respect do not track requests and even gives you the tools to enable a user to disable tracking.
I've used sessionStorage in the example above but that can be switched out to use localStorage or cookies; if using cookies this needs to be explained within your privacy policy or terms and conditions.
The conditional statement can be used around every tracking function regardless of service.