How to Make Setinterval Also Work When a Tab Is Inactive in Chrome

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

On most browsers inactive tabs have low priority execution and this can affect JavaScript timers.

If the values of your transition were calculated using real time elapsed between frames instead fixed increments on each interval, you not only workaround this issue but also can achieve a smother animation by using requestAnimationFrame as it can get up to 60fps if the processor isn't very busy.

Here's a vanilla JavaScript example of an animated property transition using requestAnimationFrame:

var target = document.querySelector('div#target')

var startedAt, duration = 3000

var domain = [-100, window.innerWidth]

var range = domain[1] - domain[0]

function start() {

startedAt = Date.now()

updateTarget(0)

requestAnimationFrame(update)

}

function update() {

let elapsedTime = Date.now() - startedAt

// playback is a value between 0 and 1

// being 0 the start of the animation and 1 its end

let playback = elapsedTime / duration

updateTarget(playback)



if (playback > 0 && playback < 1) {

// Queue the next frame

requestAnimationFrame(update)

} else {

// Wait for a while and restart the animation

setTimeout(start, duration/10)

}

}

function updateTarget(playback) {

// Uncomment the line below to reverse the animation

// playback = 1 - playback

// Update the target properties based on the playback position

let position = domain[0] + (playback * range)

target.style.left = position + 'px'

target.style.top = position + 'px'

target.style.transform = 'scale(' + playback * 3 + ')'

}

start()
body {

overflow: hidden;

}

div {

position: absolute;

white-space: nowrap;

}
<div id="target">...HERE WE GO</div>

Chrome: timeouts/interval suspended in background tabs?

I recently asked about this and it is behaviour by design. When a tab is inactive, only at a maximum of once per second the function is called. Here is the code change.

Perhaps this will help:
How can I make setInterval also work when a tab is inactive in Chrome?

TL;DR: use Web Workers.

How does Chrome (and other browsers) handle a “setTimeout” set to higher than 1000 milliseconds when a browser tab is hidden and inactive?

Most browsers throttle timeouts in inactive tabs. It means that all setTimeout's will have a minimum of 1000ms timeout. Everything longer than that should work as expected. So, answering your question, 15min timeout should not be affected.

Check out setTimeout's Timeouts in inactive tabs section on MDN: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#timeouts_in_inactive_tabs



Related Topics



Leave a reply



Submit