Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

RabinJude

How can I make setInterval also work when a tab is inactive in safari?

Safari 11.2

What is Safari doing in the JavaScript engine with respect to setTimeout() when the browser or the tab loses focus?

I have created a simple JavaScript web application that I load in Safari that calls JavaScript setTimeout() that passes another function to be executed after the set interval. The function prints the date/time to the console, the calls setTimeout() on itself again.

If the Safari tab loses focus or the browser is minimized, after some time it seems Safari stops executing the setTimeout, and until focus is returned, no activity takes place.

NOTE: No function calls are lost, they are only paused, and restarted when the browser regains focus.

I do not notice this in Firefox, Chrome or IE11.

Mac mini, iOS 10.3.1, Safari version 11.02

Posted on Feb 15, 2018 11:39 PM

Similar questions

  • window.focus() not working in Safari I am trying to test a simple JS code snippet with window.focus() Its working fine in Chrome, but not working in Safari Can someone help me to figure out the issue <!DOCTYPE html> <head> <title>Test window.focus() in Safari</title> </head> <body> <button onclick="openWindow()">Test button</button> </body> <script> function openWindow(){ var win = window.open(); win.document.write("Howdy"); win.focus(); } </script> </html> 4183 1
  • Safari on MacOS misbehaves For some number of past iterations, Safari - although my favourite browser - has to take a back seat as I use Chrome and Brave to navigate some webpages; Feedback - Safari - Apple - for example this Apple site does not render a comment box and so I can't use Safari to log a bug; (see images attached) Then, on Amazon; https://www.amazon.co.uk/gp/video/storefront/ref=atv_nb_sports?contentType=merch&contentId=Sports&merchId=Sports - "sometimes" Safari mostly will render the page but not the "play button" when you hover over a correctly rendered element. Clearing cache, Force quitting Safari and even deleting all history may get it to behave correctly, easier to switch to another browser. Further example; https://www.britbox.co.uk/watch/Episode-3-43116 BritBox just displays a black screen. Their website is owned by iTV which also suffers from the lack of a play button at times. I use extensions; 1Password 7.9.5 and AdBlock Pro 10.1.3 but loading without extensions shows that they are not the problem. Safari; 15.5 and macOS Monterey 10.4 305 5
  • Safari 16.0 switch focus between full-screen playing video and general apps Hi, I recently updated Safari to 16.0 (17614.1.25.9.10, 17614) on M1 MacBook Air. I found out there has been an issue when switching focus (using cmd+tab) between apps and full-screen playing content. In previous version, say I play an youtube video and extend it to full screen, in the mean while, I use another app to edit something. When using cmd+tab to switch focus between full screen video and the other app, you would assume to see the video content(in full screen mode) and the app. But now when you switch focus from some app to the video you were playing in full screen, it would take you to the "Click to Exit Full Screen" page with blurred page content. This new "change" has been very annoying when switching focus between apps and video playing in full screen on safari. Does anyone know how to resolve this issue? Or this is just a bug with Safari 16.0? Thx! 775 8

Loading page content

Page content loaded

There are no replies.

JS Reference

Html events, html objects, other references, window setinterval().

Display "Hello" every second (1000 milliseconds):

Call displayHello every second:

More examples below.

Description

The setInterval() method calls a function at specified intervals (in milliseconds).

The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

1 second = 1000 milliseconds.

To execute the function only once, use the setTimeout() method instead.

To clear an interval, use the id returned from setInterval():

Then you can to stop the execution by calling clearInterval():

The clearInterval() Method

The setTimeout() Method

The clearTimeout() Method

Return Value

Advertisement

More Examples

Display the time like a digital watch:

Using clearInterval() to stop the digital watch:

Using setInterval() and clearInterval() to create a dynamic progress bar:

Toggle between two background colors once every 500 milliseconds:

Pass parameters to the function (does not work in IE9 and earlier):

However, if you use an anonymous function it works in all browsers:

Browser Support

setInterval() is supported in all browsers:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

setTimeout or setInterval not working in JavaScript [Fixed]

avatar

Last updated: Apr 4, 2024 Reading time · 7 min

banner

# Table of Contents

  • setTimeout not working in JavaScript
  • setInterval not working in JavaScript
Note: if you're running into issues when using setInterval() , click on the following subheading:

# setTimeout not working in JavaScript [Solutions]

The setTimeout function might not work in JavaScript if you call it incorrectly, e.g. by passing it the result of calling the callback function.

settimeout not working

The issue in the example is that we are calling the callback function with parentheses () in the call to setTimeout .

You can resolve the issue by removing the parentheses and passing a reference to a function to setTimeout .

passing reference to function to settimeout

The callbackFn function is invoked after 1 second (1000 milliseconds) in the example.

The setTimeout() method sets a timer that runs a function once the timer expires.

In some cases, you might want to pass one or more arguments to the function.

The greet function takes a name argument, so we used an inline arrow function in the call to setTimeout .

This way we are still passing a reference to a function to setTimeout but when the function is invoked, it returns the result of calling greet with the string bobby hadz .

passing parameter to set timeout callback

If you only pass a reference to the greet function to setTimeout , then the name parameter will be undefined .

name parameter is undefined

The previous example used an inline arrow function to resolve this, but you can also pass the parameters you want to pass to the callback function directly to setTimeout .

The third argument we passed to setTimeout is passed to the greet function when it gets called after 1 second (1000 milliseconds).

You can use this approach to supply as many parameters as necessary to the callback function.

The third and fourth arguments we passed to setTimeout get passed to the greet function when it gets called after 1 second.

You can either use an inline arrow function as we did in the previous example or supply the additional parameters after the delay parameter in the call to setTimeout , however, make sure that you aren't calling the callback function with parentheses () in the call to setTimeout .

When you add parentheses to a function, you invoke it immediately and the goal is to invoke a function after N milliseconds.

# Make sure you aren't calling setTimeout with a string instead of a function

Another common cause for setTimeout not to work is when you pass it a string instead of a function.

Here is an example.

Notice that we passed a string as the first argument to setTimeout .

The method expects to get called with a reference to a function and not a string.

Passing a reference to a function as the first argument to setTimeout works as expected.

# The delay after which setTimeout is called might not be precise

Here is an example of calling the setTimeout() method that may look confusing at first.

Running the code above produces the following output.

set timeout delay is not precise

The example tries to run a function that logs a message to the console after 0 milliseconds.

One would expect that the First line message would get printed first, however, that's not the case.

When the setTimeout() method is called, it gets added to the event table.

Only then will the event loop move the waiting events to the call stack for them to get processed.

The callback function we passed to setTimeout gets queued for execution, however, it is only executed after the call stack is empty and the second console.log() call has run.

# clearTimeout not working in JavaScript [Solved]

If you encounter issues when trying to clear the timeout with the clearTimeout method, make sure to store the timeout ID that is returned from calling setTimeout .

The example clears the timeout immediately.

You will most likely want to clear the timeout if a certain condition is met.

The setTimeout method returns an ID that can be passed to the clearTimeout() method to clear the timeout.

The clearTimeout method cancels a timeout that was previously set up by a call to setTimeout .

If you pass a parameter to the clearTimeout method that is not the ID that is returned from calling setTimeout , then the clearTimeout method does nothing.

# setInterval not working in JavaScript [Solutions]

A common reason for setInterval not to work is when you pass a string to the method instead of passing it a reference to a callback function.

passing string to set interval

Notice that we passed a string instead of a reference to a callback function to setInterval .

Instead, pass a reference to the function to setInterval .

The setInterval method takes a function and a delay in milliseconds and repeatedly calls the function with the specified delay between each call.

# Make sure you aren't calling the function you passed to setInterval

Another common reason for setInterval not to work is if you invoke the callback function you passed to the method with parentheses () .

invoking callback function when calling set interval

Notice that we used parentheses to call callbackFn() in the call to the setInterval method.

To resolve the error, remove the parentheses as setInterval expects to get called with a reference to a function and not the result of calling a function.

If you have to pass arguments to the callback function, use an inline arrow function wrapper.

The arrow function returns the result of calling greet with the string bobby hadz .

We are still passing a reference to a function to setInterval , so everything works as expected.

You can also pass arguments to the callback function by specifying them after the delay parameter in the call to setInterval .

The argument we passed after the delay of 1000 milliseconds (1 second) gets passed to the greet function after the specified delay.

The same approach can be used to pass multiple arguments to the callback function.

The code sample produces the same output however, this time we passed 2 arguments to the callback function ( greet ).

We used 1000 milliseconds as the delay in the examples.

The delay parameter is used to specify the time, in milliseconds (1000 milliseconds = 1 second), the timer should delay in between executions of the supplied function.

# clearInterval not working in JavaScript [Solved]

If you encounter issues when trying to clear the interval with the clearInterval method, make sure to store the interval ID that is returned from calling setInterval .

The example clears the interval immediately.

You will most likely want to clear the interval if a certain condition is met.

The setInterval method returns an ID that can be passed to the clearInterval() method to clear the interval.

The clearInterval method cancels a timed, repeating action that was previously set up by a call to setInterval .

If you pass a parameter to the clearInterval method that is not the ID that is returned from calling setInterval , then the clearInterval method does nothing.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Cypress verification timed out after 30000 milliseconds
  • Jest: Exceeded timeout of 5000 ms for a test. Add a timeout value to this test
  • Clear a timeout or an interval in React with hooks

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home › Forums › JavaScript › setInterval in Safari… getting syntax error

  • This topic is empty.
  • Author Posts

' src=

So I have the following javascript function:

Basically it finds the number in between a span (most likely “3”) and it makes the text “This page will be refreshed in 3…” countdown from 3 to zero, then it sends the user to a specified page.

It works beautifully in FF, but in Safari, it never counts down. In the FF console, I get no syntax errors, but in the safari console, I’m getting a syntax error on line 9.

I’m pulling my hair out and can’t seem to find anything wrong with the code. I’ve even commented out a few lines and still can’t get it to work.

' src=

From what i can gather is returning an error because sec is a string not an integer, try the below and it should work fine afterwards.

  • The forum ‘JavaScript’ is closed to new topics and replies.
  • #JavaScript

Prevent timers stopping javascript

Timers stopping or acting erratically is a common problem that occurs when you have multiple browser tabs open. Your application’s timers will stop if the page isn’t active, which can often cause bugs that are difficult to track.

This post covers how to prevent timers from stopping due to inactive browser tab in JavaScript. Let’s get started!

Why it happens

The reason this happens is due to timer throttling. When application’s tab is inactive, most browsers will throttle tab activities to preserve resources and battery life on the user’s device.

Browser throttling affects timers, audio, video, and other APIs. So if your timer function is set to run every second, it may only run once every few seconds or even minutes when the tab is inactive.

So how can you fix it? Meet Web Workers .

Web workers

Web Workers allow you to run a script operation on a different thread from your application’s main execution thread.

The timer will continue counting down even when your application’s tab becomes inactive. All major browsers support web workers, so you don’t have to worry about compatibility.

Inside a web worker, you can run almost any JavaScript code. Although, there are some things you can’t do, like manipulating the DOM or using some of the methods and properties of the global window object.

Here’s a list of all the browser APIs supported by the web workers.

Steps to fix timer problem

Now that we understand what the problem is and how web workers can help, we can move on to fixing it.

To solve this issue, we’ll use a tiny library called HackTimer . The repo includes some javascript files for loading and running the web worker, which will override your browser’s timer methods.

The script overrides setInterval , setTimeout , and other methods to make sure they run in the background which, in turn, will prevent them from getting throttled when the tab becomes inactive.

Setting it up is pretty straightforward. All you need to do is copy HackTimer.js and HackTimerWorker.js to your project. Then you need to import the HackTimer.js script at the top level of your application, as follows: import HackTimer from "./scripts/hacktimer/HackTimer";

HackTimer.js contains an IFFE that will automatically get invoked. The IFFE will override the timer functions in the window scope with its own implementation that uses web workers.

Once you’ve imported the script, the timers will continue working correctly even when your tab becomes inactive.

And that’s all there’s to it!

In this post, we covered how to prevent JavaScript timers from stopping when a browser tab is inactive. We looked at why it happens, and how web workers can help. Finally, we saw how to set up HackTimer to fix the issue.

If you’d like to get more web development, React and TypeScript tips consider following me on Twitter, where I share things as I learn them. Happy coding!

Software Development Tutorials

  • The Difference between Local Storage and Session Storage: When to Use Each
  • JavaScript Tips: How to Write Clean Functions
  • Constructor vs Prototype in JavaScript: What's the Difference?
  • Reclaiming Responsibility From Best Practices in Software Development
  • Simple guide to JavaScript Decorators

solveForum

  • Search forums
  • Solveforum All topics

[Solved] setInterval not working properly on safari web extension

  • Thread starter Saurav Pahadia
  • Start date Feb 10, 2023

Saurav Pahadia

  • Feb 10, 2023

Saurav Pahadia Asks: setInterval not working properly on safari web extension I've recently ported my chrome extension to safari using the safari web extension converter: https://developer.apple.com/documen...ensions/converting_a_web_extension_for_safari . However, I'm finding that my setInterval calls only executed a set number of times in the background page. When I open the background page for my web extension, I've tried running a simple interval to see the result: Safari Web Extension Background Page with interval stuck after running set number of times When I try the same thing for my chrome web extension, the interval runs indefinitely: Chrome Web Extension Background Page with interval running continuously If I try to run the interval after opening the dev console for any random web page in Safari, the interval works fine: Safari content page with interval running continuously Similarly, a recursive setTimeout function fails in the background page for the web extension: Recursive setTimeout function in my background page Result of recursive set timeout function in my background page (stops afterwards) I'm not sure why timers might be failing in background page for Safari. My extension works perfectly fine in chrome/brave/firefox. Thanks!  

Recent Threads

Why is it okay for my .bashrc or .zshrc to be writable by my normal user.

  • Zach Huxford
  • Jun 26, 2023
SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others. Click to expand...

SFTP user login details real-time filtering

  • Amal P Ramesh

get nat port forwarding IP address

Using docker does not give error with sudo but using ctr does on starting a container, what are some of the latest nike soccer shoes that have gained popularity among players and enthusiasts in recent years, can't change tcp/ipv4 settings on windows 10.

safari setinterval not working

Customer service access 2007 template

  • tintincutes

Latest posts

  • Latest: Aubrey Champagne
  • 20 minutes ago
  • Latest: BoyUnderTheMoon
  • 41 minutes ago
  • Latest: Haritha
  • Latest: Taieb
  • Latest: neuromouse

Newest Members

FreeOnlinecrm

DEV Community

DEV Community

Aks

Posted on Feb 19, 2018 • Updated on Mar 6, 2018

Why not to use setInterval

Recently, I came across a requirement where I had to call a function repeatedly after specific time interval, like sending ajax call at every 10 seconds. Sure, best option seems as setInterval , but it blew up my face like a cracker :)

In order to understand why setInterval is evil we need to keep in mind a fact that javascript is essentially single threaded, meaning it will not perform more than one operation at a time.

In cases when functions takes longer than delay mentioned in setInterval (like ajax call, which might it prevent from completing on time), we will find that either functions have no breathing room or setInterval breaks it's rhythm.

Try above code snippets in your console

As you can see from printed console.log statement that setInterval keeps on sending ajax calls relentlessly without caring previous call has returned or not. This can queue up a lot of requests at once on the server.

Now, let's try a synchronous operation in setInterval :

We see here when setInterval encounters time intensive operation, it does either of two things, a) try to get on track or b) create new rhythm. Here on chrome it creates a new rhythm.

In case of asynchronous operations, setTimeInterval will create long queue of requests which will be very counterproductive. In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it. Alternatively, you can use setTimeout recursively in case of time sensitive operations.

Top comments (16)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

ycmjason profile image

  • Email [email protected]
  • Location London, UK
  • Education Imperial College London
  • Work Software Engineer
  • Joined Sep 30, 2017

How about making an async version of setInterval? Something like...

So we can just do

Which would call fetch every 3000ms properly.

P.S. Haven't really tested it, just an idea...

sirius1024 profile image

  • Location Munich
  • Joined Aug 26, 2018

And handle errors:

The print is

2018-08-26 09:13:43 2018-08-26 09:13:45 2018-08-26 09:13:47 2018-08-26 09:13:49 2018-08-26 09:13:51 2018-08-26 09:13:53

akanksha_9560 profile image

  • Location Berlin, Germany
  • Education Graduate
  • Joined Jan 18, 2018

Will test it and let you know. :)

coyr profile image

  • Location Ibagué, Colombia
  • Work UX Consultant at Independent
  • Joined Nov 22, 2018

Hello, I am curious If you tested it :)

moopet profile image

  • Location Scotland
  • Education Something something cybernetics
  • Pronouns They/them
  • Work Full-stack agency person
  • Joined Aug 29, 2017

Another approach is to check that the previous process isn't still running inside the setInterval callback and choose whether to skip that iteration or to kill and restart the timer.

Better would be to trigger actions on user events rather than timed events if that's possible, or to use timers only for pure cosmetics. I don't think setInterval/setTimeout are evil as such, as long as you're careful since suddenly everything's in global scope.

There's a temptation to use them to get out of a fix, though, and I think you're definitely right to treat them as a bit of a smell.

ne0nx3r0 profile image

  • Joined Feb 20, 2018

Yeah typically I'd expect either a conditional in your response function.

That's also generally how Redux ajax requests are patterned with Redux-Thunk, you would have a conditional in your response handling to verify if it still makes sense to replace the state.

stevetaylor profile image

  • Location Sydney, AU
  • Work Frontend developer
  • Joined Mar 14, 2019

There are perfectly sane ways of using setInterval without requests backing up, e.g. (warning: untested RxJS code ahead):

belkamax05 profile image

As you can see from printed console.log statement that whole load of setInterval events arrive immediately after each other without any delay.

Didn't get a point, as I see from printed console, results are fully predicted. Every single "insideSetInterval" prints with delay of two seconds (like described in setInterval), and also - "returning from server" appears after 4 seconds since first setInterval, which was called with timeout 4000ms, where is "without any delay"?

If you speak about no delay between "returning from server" and "insideSetInterval", of course, because setTimeout with 4sec will wait until interval will be executed twice), and dont have to be in sync with interval prints. With heavy calculation it can load stack, but for simple refreshes - like a timer display update or some other light calculations - working properly, if not forget to handle instance with "clearInterval" when it's no needed anymore.

You are right, for light calculations it does not make much of a difference. But for example gmail has to refresh your inbox when new mail arrives, if we were to do it by setTimeInterval, we will queue a lot of requests at server. I have changed the contents of the blog. Please go through that maybe it will put across my point clearly.

Thanks for your reply, yes. I agree, if there will be heavy calculation or long time awaiting, it will work unpredictable. For heavy calculations I would like to use some kind of state machines, which will not make additional request if previous one still in pending state (can be timeout of it). Unfortunatelly, we cannot stop executing request to a server, but we can mark it in client side as NOT VALID (throw exception after some timeout), but this will continue execution on server and in case of non-stop requests, they will do DoS attack. But that's also not a setInterval and setTimeout case, there have to be much more code over it, to prevent that kind of issues. If server taking decision when content have to be updated - WebSockets can prevent lot of issues, IMHO they are ready to be used in production.

juanmendes profile image

  • Location Boston
  • Work Staff Engineer at VMware
  • Joined Oct 21, 2019

Another reason is because setIntervals stop running if your browser window loses focus, your callbacks will queue up and run once the page has focus again. Or even worse, they will be dropped. See jsfiddle.net/mendesjuan/y3h1n6mk/

antialias profile image

  • Joined Sep 30, 2019
In order to understand why setInterval is evil

Thanks for the detailed explanation of setInterval in sync and async contexts, but why is it this "evil"? With a proper understanding of how the js event loop works, it's easy to understand the reason why a "new rhythm" gets established in the sync case, and why it doesn't in the async case.

tea247 profile image

  • Location Trenches
  • Education Certs and Vocational
  • Pronouns He/Him
  • Work Perzsi, Calculate All, Payspieloo, Asecretword
  • Joined Dec 29, 2020

You don't need to create the variable, but it's a good practice as you can use that variable with clearInterval to stop the currently running interval.

var int = setInterval("doSomething()", 5000 ); /* 5 seconds / var int = setInterval(doSomething, 5000 ); / same thing, no quotes, no parens */

If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond the first two to setInterval.

Without overlapping

setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what. Even if the function doSomething() takes long than 5 seconds to run. That can create issues. If you just want to make sure there is that pause in between runnings of doSomething, you can do this: (function(){ doSomething(); setTimeout(arguments.callee, 5000); })()

For My Chat App function messageCount(){ var bond=$('#active-friend-status').attr('bond'); if (bond!='') { $.ajax({ url : 'messageCount', type : 'GET', data : {'messageCount' : true, 'bond' : bond}, success : function(data) { var messageCount = parseInt(data); newCount(messageCount); }, error : function() { } }) } function update(messageCount, newCount) { var bond=$('#active-friend-status').attr('bond'); if (messageCount<newCount) { $('#active-message-box').load('message?bond='+bond+''); console.log('Updated'); } } function newCount(messageCount) { var m = messageCount; setTimeout(function newCount(m) { var bond=$('#active-friend-status').attr('bond'); if (bond!=''){ $.ajax({ url : 'messageCount', type : 'GET', data : {'messageCount' : true, 'bond' : bond}, success : function(data) { var newCount = parseInt(data); update(messageCount, newCount); }, error : function() { } }) } }, 3000); } } (function(){ messageCount(); setTimeout(arguments.callee, 2000); })()

prafullsalunke profile image

  • Joined Dec 6, 2017

I get what you are trying to say here. A small mistake here though. The timeout in fakeCallToServer should have been a random from 200ms to 15 sec to mimic an actual api response scenario.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

falselight profile image

FREE: Password Generator ⚡ PRO (extension/add-on) + [source code]

YURIIDE - Jun 2

inezabonte profile image

Rebuilding My Blog: From Next.js to Astro

Ineza Bonté Grévy - May 24

sh20raj profile image

Install Homebrew on Amazon Linux in AWS Cloud9

Sh Raj - Jun 2

sudhanshuambastha profile image

Sudhanshu Ambastha - Jun 2

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Web Development Updates

What Happens to setTimeout() / setInterval() Timers Running on Inactive Browser Tabs ?

safari setinterval not working

Use-Cases of this tutorial

  • Know how browser modifies setTimeout() / setInterval() behavior that execute on background tabs.

Time delay for setTimeout() / setInterval() methods executing on inactive browser tabs are set to one second regardless of their value defined in code.

Timers methods setTimeout() / setInterval() running on background tabs can be resource exhausting. An application running callbacks at very short intervals in a background tab may drain a lot of memory to the point that the working of the currently active tab may be impacted. In the worst case, the browser may crash, or battery of the device would be rapidly used up.

In such cases, it makes sense to place some restrictions on the timers running in background tabs.

Browsers do exactly this. For inactive tabs, they automatically throttle timers to run every 1 second, regardless of the original delay specified in the code . For example, if the code originally used setInterval() to run some code every 50 ms, once the application is moved to a background tab, the interval automatically becomes 1000 ms (1 second).

However once the tab is re-activated, the original interval or delay returns to the original value .

Update, Jan 2021 : From Chrome 88+, timers can be throttled to 1 minute in certain conditions. Read more .

Making Sure Timer Throttling Does Not Result in Buggy Behavior

It is important to consider the scenario when the application's timers may get throttled when user moves to a different tab or minimizes the browser. For example, if the application runs an animation using setInterval() , the user may see a distorted form of the animation when he returns back to the original tab. This distortion may happen because the code that was supposed to execute every few milliseconds, ran every 1 second while the tab was inactive.

The Page Visibility API can be used to find if the user moved away from the tab, or came back to the tab again. Knowing this, timers can be temporarily paused when the tab is inactive.

Useful Resources

  • Google Chrome policies for running timers in the background .

In this Tutorial

Related tutorials.

If Safari isn't loading websites or quits on your iPhone, iPad, or iPod touch

If you can't load a website or webpage, or Safari quits unexpectedly, follow these steps.

Connect to a different network

Try to load a website, like www.apple.com , using cellular data. If you don't have cellular data, connect to a different Wi-Fi network , then load the website.

If you're using a VPN (Virtual Private Network), check your VPN settings . If you have a VPN turned on, some apps or websites might block content from loading.

Restart your device

Turn off your device and turn it on again.

Restart your iPhone

Restart your iPad

Restart your iPod touch

Clear website data

You can clear website data occasionally to improve Safari performance.

Go to Settings > Safari.

Tap Clear History and Website Data.

Tap Clear History to confirm.

Turn on JavaScript

Turn on JavaScript if it's not already on.

Go to Settings > Safari > Advanced.

Turn on JavaScript.

Get more help

If the issue continues and only affects a certain website or webpage, check if you have Private Relay turned on. You can temporarily turn off Private Relay in iCloud Settings . If Safari still doesn't load websites and you tried all of these steps, contact the website developer for more help.

safari setinterval not working

Explore Apple Support Community

Find what’s been asked and answered by Apple customers.

safari setinterval not working

Contact Apple Support

Need more help? Save time by starting your support request online and we'll connect you to an expert.

Adobe Acrobat Learn & Support

Learn  what's new  in Acrobat!

Get Started

Download, find membership help, and learn the basics.

Find tutorials from novice to expert to help you expand your skills.

Get quick answers and step-by-step instructions.

Troubleshooting & help

Get help  downloading and installing  Acrobat, Acrobat 2020, 2017, Acrobat Reader, and more, along with common installation and troubleshooting issues.

See how to  uninstall and reinstall  Acrobat on Windows or macOS, as a trial, and on a second computer.

Your individual Acrobat license lets you  install Acrobat on more than one computer , and activate (sign in) on up to two computers.

Fix errors with your Adobe apps  if you received an error code or number, or get help with common  Acrobat installation errors and solutions .

Still need help? Find more download and install solutions . 

Get to know the Acrobat interface . Learn how the Acrobat Tool Center makes it easy to find the right tool and complete almost any task with your PDFs.

Many factors can prevent a PDF from opening. To get to the root of the problem, see  Can't open PDF .

Many factors can prevent you from editing a PDF. For information about how to edit a PDF, see  Edit PDF help hub page .

Windows 10 uses Microsoft Edge to open PDFs. Learn how to  make Acrobat or Reader the default owner of PDFs  instead.

Sign in to your  Adobe account . Under the  Password  section, select  Change  for C urrent Password , and then follow the onscreen instructions.

Forgot your password?  Learn how to  reset it .

Follow these  Update your credit card and billing information .

Converting your trial to a paid membership is easy. Follow these step-by-step instructions to  upgrade and start your membership .

Learn how to  cancel your subscription  and  understand the Adobe subscription terms .

Still need help? Find more  account, billing, and plan answers .

Ask questions and get answers from experts.

Ask now >

Acrobat subforums

Installing, Updating, & Using Acrobat

Document Cloud PDF services

Creating PDFs

Related Apps & Services

Document Cloud

Acrobat Reader

Adobe Acrobat Sign

Adobe Acrobat Sign - Mobile

Share this page

Language Navigation

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

setTimeout() global function

Note: This feature is available in Web Workers .

The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

A function to be executed after the timer expires.

An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle.

Note that in either case, the actual delay may be longer than intended; see Reasons for delays longer than specified below.

Also note that if the value isn't a number, implicit type coercion is silently done on the value to convert it to a number — which can lead to unexpected and surprising results; see Non-number delay values are silently coerced into numbers for an example.

Additional arguments which are passed through to the function specified by functionRef .

Return value

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout() . This value can be passed to clearTimeout() to cancel the timeout.

It is guaranteed that a timeoutID value will never be reused by a subsequent call to setTimeout() or setInterval() on the same object (a window or a worker). However, different objects use separate pools of IDs.

Description

Timeouts are cancelled using clearTimeout() .

To call a function repeatedly (e.g., every N milliseconds), consider using setInterval() .

Non-number delay values are silently coerced into numbers

If setTimeout() is called with delay value that's not a number, implicit type coercion is silently done on the value to convert it to a number. For example, the following code incorrectly uses the string "1000" for the delay value, rather than the number 1000 – but it nevertheless works, because when the code runs, the string is coerced into the number 1000 , and so the code executes 1 second later.

But in many cases, the implicit type coercion can lead to unexpected and surprising results. For example, when the following code runs, the string "1 second" ultimately gets coerced into the number 0 — and so, the code executes immediately, with zero delay.

Therefore, don't use strings for the delay value but instead always use numbers:

Working with asynchronous functions

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

See the following example:

Notice that the first function does not create a 5-second "pause" before calling the second function. Instead, the first function is called, but waits 5 seconds to execute. While the first function is waiting to execute, the second function is called, and a 3-second wait is applied to the second function before it executes. Since neither the first nor the second function's timers have completed, the third function is called and completes its execution first. Then the second follows. Then finally the first function is executed after its timer finally completes.

To create a progression in which one function only fires after the completion of another function, see the documentation on Promises .

The "this" problem

When you pass a method to setTimeout() , it will be invoked with a this value that may differ from your expectation. The general issue is explained in detail in the JavaScript reference .

Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind , it will default to the window (or global ) object, even in strict mode . It will not be the same as the this value for the function that called setTimeout .

The above works because when myMethod is called, its this is set to myArray by the call, so within the function, this[sProperty] is equivalent to myArray[sProperty] . However, in the following:

The myArray.myMethod function is passed to setTimeout , then when it's called, its this is not set, so it defaults to the window object.

There's also no option to pass a thisArg to setTimeout as there is in Array methods such as forEach() and reduce() . As shown below, using call to set this doesn't work either.

Use a wrapper function

A common way to solve the problem is to use a wrapper function that sets this to the required value:

The wrapper function can be an arrow function:

Alternatively, you can use bind() to set the value of this for all calls to a given function:

Passing string literals

Passing a string instead of a function to setTimeout() has the same problems as using eval() .

A string passed to setTimeout() is evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

Reasons for delays longer than specified

There are a number of reasons why a timeout may take longer to fire than anticipated. This section describes the most common reasons.

Nested timeouts

As specified in the HTML standard , browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times.

This can be seen in the following example, in which we nest a call to setTimeout with a delay of 0 milliseconds, and log the delay each time the handler is called. The first four times, the delay is approximately 0 milliseconds, and after that it is approximately 4 milliseconds:

Timeouts in inactive tabs

To reduce the load (and associated battery usage) from background tabs, browsers will enforce a minimum timeout delay in inactive tabs. It may also be waived if a page is playing sound using a Web Audio API AudioContext .

The specifics of this are browser-dependent:

  • Firefox Desktop and Chrome both have a minimum timeout of 1 second for inactive tabs.
  • Firefox for Android has a minimum timeout of 15 minutes for inactive tabs and may unload them entirely.
  • Firefox does not throttle inactive tabs if the tab contains an AudioContext .

Throttling of tracking scripts

Firefox enforces additional throttling for scripts that it recognizes as tracking scripts. When running in the foreground, the throttling minimum delay is still 4ms. In background tabs, however, the throttling minimum delay is 10,000 ms, or 10 seconds, which comes into effect 30 seconds after a document has first loaded.

See Tracking Protection for more details.

Late timeouts

The timeout can also fire later than expected if the page (or the OS/browser) is busy with other tasks. One important case to note is that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated. For example:

Will write to the console:

This is because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. Currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected.

Deferral of timeouts during pageload

Firefox will defer firing setTimeout() timers while the current tab is loading. Firing is deferred until the main thread is deemed idle (similar to window.requestIdleCallback() ), or until the load event is fired.

WebExtension background pages and timers

In WebExtensions , setTimeout() does not work reliably. Extension authors should use the alarms API instead.

Maximum delay value

Browsers store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.

Setting and clearing timeouts

The following example sets up two simple buttons in a web page and hooks them to the setTimeout() and clearTimeout() routines. Pressing the first button will set a timeout which shows a message after two seconds and stores the timeout id for use by clearTimeout() . You may optionally cancel this timeout by pressing on the second button.

See also the clearTimeout() example .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Polyfill of setTimeout which allows passing arguments to the callback in core-js
  • clearTimeout
  • setInterval()
  • window.requestAnimationFrame
  • queueMicrotask()

IMAGES

  1. setInterval in Safari... getting syntax error

    safari setinterval not working

  2. setInterval not working properly on safari web extension

    safari setinterval not working

  3. setInterval not working properly on safari web extension

    safari setinterval not working

  4. Safari Not Working? Here's The Complete Troubleshooting Guide & Fix

    safari setinterval not working

  5. setInterval not working properly on safari web extension

    safari setinterval not working

  6. setInterval not working properly on safari web extension

    safari setinterval not working

VIDEO

  1. Safari is AI Now!

  2. The only regret is the path not taken

  3. How to Fix Safari Slow Download Issues on iPhone || Safari Browser Download Speed Slow

  4. setInterval() should not used on server .NUXT 3 FIX

  5. how to use the JavaScript setInterval() method #coding #tutorial #javascript #shorts

  6. setInterval & clearInterval in React Hooks

COMMENTS

  1. Javascript setinterval function not working on MAC safari

    @user1244197: Well, It has to do with the value of this in a function. The value of this changes based on how the function is invoked. Call .bind on a function returns a new function with the value of this bound to the first argument that you passed to .bind.That way it doesn't really matter how the function is invoked, the this value will be the value you expect.

  2. How can I make setInterval also work when…

    The function prints the date/time to the console, the calls setTimeout () on itself again. If the Safari tab loses focus or the browser is minimized, after some time it seems Safari stops executing the setTimeout, and until focus is returned, no activity takes place. NOTE: No function calls are lost, they are only paused, and restarted when the ...

  3. setInterval() global function

    setInterval () global function. Note: This feature is available in Web Workers. The setInterval() method, offered on the Window and WorkerGlobalScope interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can ...

  4. Window setInterval() Method

    Description. The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

  5. Why setInterval does not work properly on safari

    Why setInterval does not work properly on safari ? I created simple setInterval method to change text of a header but it doesn't work properly on safari no problem on chrome though. this is video of the problem. Share Add a Comment. Sort by: Best. Open comment sort options ...

  6. setTimeout or setInterval not working in JavaScript [Fixed]

    The setInterval method takes a function and a delay in milliseconds and repeatedly calls the function with the specified delay between each call. # Make sure you aren't calling the function you passed to setInterval. Another common reason for setInterval not to work is if you invoke the callback function you passed to the method with ...

  7. setInterval in Safari... getting syntax error

    So I have the following javascript function:

  8. Why Javascript timer is unreliable, and how can you fix it

    Hence, when we call the function hangTheBrowser, the running loop blocks the main thread, thereby pausing the timer until it finishes executing. However, there are a few clever techniques which we can employ to make the timer behave as we expect. Below I am listing four such techniques. Using Date Object.

  9. window. setInterval() not working in Safari

    [COLOR="Blue"]window.setInterval("refreshProgress()", 1500); [/COLOR] which is not working in Safari. It works fine in Firefox though. (The refreshProgress() method is actually part of some ajax code to call a java Listener listing on a file upload. That part is working fine. I don't think the problem is there)

  10. How to Prevent the Timers from Stopping Due to Browser Tab Inactivity

    The script overrides setInterval, setTimeout, and other methods to make sure they run in the background which, in turn, will prevent them from getting throttled when the tab becomes inactive. Setting it up is pretty straightforward. All you need to do is copy HackTimer.js and HackTimerWorker.js to your project. Then you need to import the ...

  11. setInterval

    Automating Function Timing. clearInterval. Stops the function associated with the identifier from repeating. setTimeout. Executes a given function after a set amount of time. clearTimeout. Stops the function associated with the identifier from executing. Repeatedly executes a given function at the given time interval.

  12. [Solved] setInterval not working properly on safari web extension

    Saurav Pahadia Asks: setInterval not working properly on safari web extension I've recently ported my chrome extension to safari using the safari web...

  13. How to Fix setTimeout/setInterval Not Working Properly in Chrome

    Solution. One solution to this problem is to use a web worker to simulate the timer in JavaScript. A web worker is a separate JavaScript thread that can run in the background, independent of the ...

  14. Why not to use setInterval

    var int = setInterval(doSomething, 5000 ); / same thing, no quotes, no parens */ If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond the first two to setInterval. Without overlapping. setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what.

  15. Javascript setInterval not working

    The solution is to give setInterval a function to run instead of a string. So, in this case: var run = setInterval(funcName, 10000); Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName ...

  16. setTimeout() / setInterval() Methods Running on Inactive Tab

    Time delay for setTimeout () / setInterval () methods executing on inactive browser tabs are set to one second regardless of their value defined in code. Timers methods setTimeout () / setInterval () running on background tabs can be resource exhausting. An application running callbacks at very short intervals in a background tab may drain a ...

  17. If Safari isn't loading websites or quits on your iPhone, iPad, or iPod

    Connect to a different network. Try to load a website, like www.apple.com, using cellular data. If you don't have cellular data, connect to a different Wi-Fi network, then load the website. If you're using a VPN (Virtual Private Network), check your VPN settings. If you have a VPN turned on, some apps or websites might block content from loading.

  18. Javascript setInterval not running in Safari on windows, works in

    So i am getting to know Canvas element and i made simple Canvas based gallery to get me started. I use setInterval to update src of my Image and than onLoad to draw it in canvas. Problem is that it works in Chrome but not in Safari or IE. var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var img = new Image();

  19. Adobe Acrobat Learn & Support

    Get started with Adobe Acrobat. Find tutorials, the user guide, answers to common questions, and help from the community forum.

  20. setTimeout() global function

    Working with asynchronous functions. setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.