I'm loading a front-end site from Wordpress using a HTML 5 Blank Child Theme. I have a logo effect using particle slider for when I have a screen size of >960px; for screen sizes <960px I have a flat logo image. It all works fine on both Firefox and Google Chrome but when I re-size between logos on Safari the page has to be refreshed manually (i.e. by pressing cmd+r) before the PS effect shows again. The code was sourced from an original question I posted here - Original Stack Q&A
Here's the javascript code I'm now using -
particle-slider.php
<?php /* Template Name: particle-slider */ ?>
<!-- particle-slider template -->
<div id="particle-slider">
<div class="slides">
<div class="slide" data-src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png"></div>
</div>
<canvas class="draw" style="width: 100%; height: 100%;"></canvas>
</div>
<script type="text/javascript">
var ps = new ParticleSlider({ 'width':'1400', 'height': '600' });
// patch nextFrame to track failure/success
var nextFrameCalled = false;
ps.oldNextFrame = ps.nextFrame;
ps.nextFrame = function () {
try {
ps.oldNextFrame.apply(this, arguments);
nextFrameCalled = true;
} catch (e) {
console.log(e);
nextFrameCalled = false;
}
};
var addEvent = function (object, type, callback) {
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on" + type] = callback;
}
};
var oldWidth = window.innerWidth;
addEvent(window, 'resize', function () {
var newWidth = window.innerWidth;
if (newWidth >= 960 && oldWidth < 960) {
console.log("Restarting particle slider " + newWidth);
ps.resize();
if (!nextFrameCalled)
ps.nextFrame(); // force restart animation
else {
// ensure that nextFrameCalled is not still true from previous cycle
nextFrameCalled = false;
setTimeout(function () {
if (!nextFrameCalled)
ps.nextFrame(); // force restart animation
}, 100);
}
}
oldWidth = newWidth;
});
</script>
<div id="logo"> <img src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logo.png"> </div>
<!-- particle-slider template -->
I need the same effect as is seen on this site here - where the logo switches from particle to static as the page is re-sized. The particle logo re-appears perfectly.
All other relevant code is linked to the original question as nothing has changed. I'm not seeing anything in the console to suggest why it's not working.
The resize event can fire multiple times, and within that event anything you put in a setTimeout will get called after the current code block has executed. It's hard to say for sure without picking apart ParticleSlider, but I think the mix of global variables (nextFrameCalled, oldWidth) and callbacks firing out of your expected order is the cause.
I think the intention is to debounce the forced restart - you want to call ParticleSlider.nextFrame() but if it's already been called you want to wait 100ms first.
Looking at the answer you've adapted for this question that appears to be a workaround for the canvas element not being visible on requestAnimationFrame - that might still not be available after 100ms or after the ParticleSlider.nextFrame() has been called multiple times in an attempt to get it to fire.
From your original question and selected answer I think you need to ParticleSlider.init() to reset the component, but the flashing you're seeing is due to the fact that it takes a while to run every time it's called. ParticleSlider.nextFrame() doesn't take as long (and uses requestAnimationFrame to avoid jank) but doesn't create the canvas on resize in Safari.
So, to fix:
Use ParticleSlider.init()
Debounce the resize event so you're not firing it lots of times
Fire it once a short delay after the user has stopped firing resize events.
Code will be something like:
var timeout = null;
window.addEventListener('resize', function() {
// Clear any existing debounced re-init
clearTimeout(timeout);
// Set up a re-init to fire in 1/2 a secound
timeout = setTimeout(function() {
ps.init();
}, 500);
});
You'll still see the flash and the delay as the component re-initialises, but only once.
I'd add that ParticleSlider has been deprecated by the authors and replaced with NextParticle - probably to fix these kinds of issues (in fact it has specific features to handle resizing). As it is a paid for component I'd suggest asking them for the help with this, as you should get your money's worth (or switch to an open source component where you can fix these bugs yourself).
So, I've finally figured this out by retracing my steps using the Q&A from before. Previously there seemed to be an issue with some of the sample links but one appears to work now - example.
I went into the page inspector and noticed a few differences between the code firing this example and the one in the actual answer that was causing the logo to flicker like a light bulb. This is the code I have now put into the wordpress site -
<script type="text/javascript">
//wait until the DOM is ready to be queried
(function() {//document.addEventListener('DOMContentLoaded', function() { //DOM-ready callback
var ps, timeout;
var img1 = new Image();
img1.src = '<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png';//havoc_logo_e6os2n.png';
var imgs = [ img1 ];
handlePS();
window.addEventListener('resize', function() {
//https://davidwalsh.name/javascript-debounce-function
if (timeout) { //check if the timer has been set
clearTimeout(timeout); //clear the timer
}
//set a timer
timeout = setTimeout(handlePS, 250);
});
function handlePS() {
if (document.body.clientWidth >= 960) {
//check if ps is assigned as an instance of the ParticleSlider
if (ps != undefined && typeof ps !== null) {
ps.init(); //refresh the particle slider since it exists
console.log('called init on ps');
} else {
if (window.location.search.indexOf('d=1') > -1) {
debugger;
}
//otherwise create a new instance of the particle slider
ps = new ParticleSlider({
width: 1400,
height: 600,
imgs: imgs
});
}
}
else {
//when the flat logo is displayed, get rid of the particle slider instance
// delete ps;
ps = null;
}
}
})();
</script>
It now works fine across all the main browsers - Chrome/Safari/Firefox. It still feels a bit clunky as it pushes the rest of the page down whilst it is re-sizing and it takes probably a few seconds more than I'd like - not sure if there's a timer option to speed the reanimation up? Otherwise, everything is working fine.
I have a setInterval running a piece of code 30 times a second. This works great, however when I select another tab (so that the tab with my code becomes inactive), the setInterval is set to an idle state for some reason.
I made this simplified test case (http://jsfiddle.net/7f6DX/3/):
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.css("left", a)
}, 1000 / 30);
If you run this code and then switch to another tab, wait a few seconds and go back, the animation continues at the point it was when you switched to the other tab.
So the animation isn't running 30 times a second in case the tab is inactive. This can be confirmed by counting the amount of times the setInterval function is called each second - this will not be 30 but just 1 or 2 if the tab is inactive.
I guess that this is done by design so as to improve system performance, but is there any way to disable this behavior?
It’s actually a disadvantage in my scenario.
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>
For Background Tasks (non-UI related)
#UpTheCreek comment:
Fine for presentation issues, but still
there are some things that you need to keep running.
If you have background tasks that needs to be precisely executed at given intervals, you can use HTML5 Web Workers. Take a look at Möhre's answer below for more details...
CSS vs JS "animations"
This problem and many others could be avoided by using CSS transitions/animations instead of JavaScript based animations which adds a considerable overhead. I'd recommend this jQuery plugin that let's you take benefit from CSS transitions just like the animate() methods.
I ran into the same problem with audio fading and HTML5 player. It got stuck when tab became inactive.
So I found out a WebWorker is allowed to use intervals/timeouts without limitation. I use it to post "ticks" to the main javascript.
WebWorkers Code:
var fading = false;
var interval;
self.addEventListener('message', function(e){
switch (e.data) {
case 'start':
if (!fading){
fading = true;
interval = setInterval(function(){
self.postMessage('tick');
}, 50);
}
break;
case 'stop':
clearInterval(interval);
fading = false;
break;
};
}, false);
Main Javascript:
var player = new Audio();
player.fader = new Worker('js/fader.js');
player.faderPosition = 0.0;
player.faderTargetVolume = 1.0;
player.faderCallback = function(){};
player.fadeTo = function(volume, func){
console.log('fadeTo called');
if (func) this.faderCallback = func;
this.faderTargetVolume = volume;
this.fader.postMessage('start');
}
player.fader.addEventListener('message', function(e){
console.log('fader tick');
if (player.faderTargetVolume > player.volume){
player.faderPosition -= 0.02;
} else {
player.faderPosition += 0.02;
}
var newVolume = Math.pow(player.faderPosition - 1, 2);
if (newVolume > 0.999){
player.volume = newVolume = 1.0;
player.fader.postMessage('stop');
player.faderCallback();
} else if (newVolume < 0.001) {
player.volume = newVolume = 0.0;
player.fader.postMessage('stop');
player.faderCallback();
} else {
player.volume = newVolume;
}
});
There is a solution to use Web Workers (as mentioned before), because they run in separate process and are not slowed down
I've written a tiny script that can be used without changes to your code - it simply overrides functions setTimeout, clearTimeout, setInterval, clearInterval.
Just include it before all your code.
more info here
Both setInterval and requestAnimationFrame don't work when tab is inactive or work but not at the right periods. A solution is to use another source for time events. For example web sockets or web workers are two event sources that work fine while tab is inactive. So no need to move all of your code to a web worker, just use worker as a time event source:
// worker.js
setInterval(function() {
postMessage('');
}, 1000 / 50);
.
var worker = new Worker('worker.js');
var t1 = 0;
worker.onmessage = function() {
var t2 = new Date().getTime();
console.log('fps =', 1000 / (t2 - t1) | 0);
t1 = t2;
}
jsfiddle link of this sample.
Just do this:
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.stop(true,true).css("left", a);
}, 1000 / 30);
Inactive browser tabs buffer some of the setInterval or setTimeout functions.
stop(true,true) will stop all buffered events and execute immediatly only the last animation.
The window.setTimeout() method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
For me it's not important to play audio in the background like for others here, my problem was that I had some animations and they acted like crazy when you were in other tabs and coming back to them. My solution was putting these animations inside if that is preventing inactive tab:
if (!document.hidden){ //your animation code here }
thanks to that my animation was running only if tab was active.
I hope this will help someone with my case.
I think that a best understanding about this problem is in this example: http://jsfiddle.net/TAHDb/
I am doing a simple thing here:
Have a interval of 1 sec and each time hide the first span and move it to last, and show the 2nd span.
If you stay on page it works as it is supposed.
But if you hide the tab for some seconds, when you get back you will see a weired thing.
Its like all events that didn't ucur during the time you were inactive now will ocur all in 1 time. so for some few seconds you will get like X events. they are so quick that its possible to see all 6 spans at once.
So it seams chrome only delays the events, so when you get back all events will occur but all at once...
A pratical application were this ocur iss for a simple slideshow. Imagine the numbers being Images, and if user stay with tab hidden when he came back he will see all imgs floating, Totally mesed.
To fix this use the stop(true,true) like pimvdb told.
THis will clear the event queue.
Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head> and it will patch setInterval and setTimeout with ones that use WebWorker.
Playing an audio file ensures full background Javascript performance for the time being
For me, it was the simplest and least intrusive solution - apart from playing a faint / almost-empty sound, there are no other potential side effects
You can find the details here: https://stackoverflow.com/a/51191818/914546
(From other answers, I see that some people use different properties of the Audio tag, I do wonder whether it's possible to use the Audio tag for full performance, without actually playing something)
I bring here a simple solution for anyone who is trying to get around this problem in a timer function, where as #kbtzr mentioned in another answer we can use the Date object instead of fixed increments to calculate the time that has passed since the beginning, which will work even if you are out from the application's tab.
This is the example HTML.
<body>
<p id="time"></p>
</body>
Then this JavaScript:
let display = document.querySelector('#time')
let interval
let time
function startTimer() {
let initialTime = new Date().getTime()
interval = setInterval(() => {
let now = new Date().getTime()
time = (now - initialTime) + 10
display.innerText = `${Math.floor((time / (60 * 1000)) % 60)}:${Math.floor((time / 1000) % 60)}:${Math.floor((time / 10) % 100)}`
}, 10)
}
startTimer()
That way, even if the interval value is increased for performance reasons of inactive tabs, the calculation made will guarantee the correct time. This is a vanilla code, but I used this logic in my React application, and you can modify it for wherever you need as well.
It is quite old question but I encountered the same issue.
If you run your web on chrome, you could read through this post Background Tabs in Chrome 57.
Basically the interval timer could run if it haven't run out of the timer budget.
The consumption of budget is based on CPU time usage of the task inside timer.
Based on my scenario, I draw video to canvas and transport to WebRTC.
The webrtc video connection would keep updating even the tab is inactive.
However you have to use setInterval instead of requestAnimationFrame but itt is not recommended for UI rendering though.
It would be better to listen visibilityChange event and change render mechenism accordingly.
Besides, you could try what Kaan Soral suggests and it should works based on the documentation.
I modified Lacerda's response, by adding a functioning UI.
I added start/resume/pause/stop actions.
const
timer = document.querySelector('.timer'),
timerDisplay = timer.querySelector('.timer-display'),
toggleAction = timer.querySelector('[data-action="toggle"]'),
stopAction = timer.querySelector('[data-action="stop"]'),
tickRate = 10;
let intervalId, initialTime, pauseTime = 0;
const now = () => new Date().getTime();
const formatTime = (hours, minutes, seconds) =>
[hours, minutes, seconds]
.map(v => `${isNaN(v) ? 0 : v}`.padStart(2, '0'))
.join(':');
const update = () => {
let
time = (now() - initialTime) + 10,
hours = Math.floor((time / (60000)) % 60),
minutes = Math.floor((time / 1000) % 60),
seconds = Math.floor((time / 10) % 100);
timerDisplay.textContent = formatTime(hours, minutes, seconds);
};
const
startTimer = () => {
initialTime = now();
intervalId = setInterval(update, tickRate);
},
resumeTimer = () => {
initialTime = now() - (pauseTime - initialTime);
intervalId = setInterval(update, tickRate);
},
pauseTimer = () => {
clearInterval(intervalId);
intervalId = null;
pauseTime = now();
},
stopTimer = () => {
clearInterval(intervalId);
intervalId = null;
initialTime = undefined;
pauseTime = 0;
},
restartTimer = () => {
stopTimer();
startTimer();
};
const setButtonState = (button, state, text) => {
button.dataset.state = state;
button.textContent = text;
};
const
handleToggle = (e) => {
switch (e.target.dataset.state) {
case 'pause':
setButtonState(e.target, 'resume', 'Resume');
pauseTimer();
break;
case 'resume':
setButtonState(e.target, 'pause', 'Pause');
resumeTimer();
break;
default:
setButtonState(e.target, 'pause', 'Pause');
restartTimer();
}
},
handleStop = (e) => {
stopTimer();
update();
setButtonState(toggleAction, 'initial', 'Start');
};
toggleAction.addEventListener('click', handleToggle);
stopAction.addEventListener('click', handleStop);
update();
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
background: #000;
}
.timer {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.5em;
}
.timer .timer-display {
font-family: monospace;
font-size: 3em;
background: #111;
color: #8F8;
border: thin solid #222;
padding: 0.25em;
}
.timer .timer-actions {
display: flex;
justify-content: center;
gap: 0.5em;
}
.timer .timer-actions button[data-action] {
font-family: monospace;
width: 6em;
border: thin solid #444;
background: #222;
color: #EEE;
padding: 0.5em;
cursor: pointer;
text-transform: uppercase;
}
.timer .timer-actions button[data-action]:hover {
background: #444;
border: thin solid #666;
color: #FFF;
}
<div class="timer">
<div class="timer-display"></div>
<div class="timer-actions">
<button data-action="toggle" data-state="initial">Start</button>
<button data-action="stop">Stop</button>
</div>
</div>
Note: This solution is not suitable if you like your interval works on the background, for example, playing audio or something else. But if you are confused for example about your animation not working properly when coming back to your page or tab, this is a good solution.
There are many ways to achieve this goal, maybe the "WebWorkers" is the most standard one but certainly, it's not the easiest and handy one, especially If you don't have enough Time, so you can try this way:
The basic concept:
build a name for your interval(or animation) and set your interval(animation), so it would run when user first time open your page : var interval_id = setInterval(your_func, 3000);
by $(window).focus(function() {}); and $(window).blur(function() {}); you can clearInterval(interval_id) everytime browser(tab) is deactived and ReRun your interval(animation) everytime browser(tab) would acive again by interval_id = setInterval();
Sample code:
var interval_id = setInterval(your_func, 3000);
$(window).focus(function() {
interval_id = setInterval(your_func, 3000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
Here's my rough solution
(function(){
var index = 1;
var intervals = {},
timeouts = {};
function postMessageHandler(e) {
window.postMessage('', "*");
var now = new Date().getTime();
sysFunc._each.call(timeouts, function(ind, obj) {
var targetTime = obj[1];
if (now >= targetTime) {
obj[0]();
delete timeouts[ind];
}
});
sysFunc._each.call(intervals, function(ind, obj) {
var startTime = obj[1];
var func = obj[0];
var ms = obj[2];
if (now >= startTime + ms) {
func();
obj[1] = new Date().getTime();
}
});
}
window.addEventListener("message", postMessageHandler, true);
window.postMessage('', "*");
function _setTimeout(func, ms) {
timeouts[index] = [func, new Date().getTime() + ms];
return index++;
}
function _setInterval(func, ms) {
intervals[index] = [func, new Date().getTime(), ms];
return index++;
}
function _clearInterval(ind) {
if (intervals[ind]) {
delete intervals[ind]
}
}
function _clearTimeout(ind) {
if (timeouts[ind]) {
delete timeouts[ind]
}
}
var intervalIndex = _setInterval(function() {
console.log('every 100ms');
}, 100);
_setTimeout(function() {
console.log('run after 200ms');
}, 200);
_setTimeout(function() {
console.log('closing the one that\'s 100ms');
_clearInterval(intervalIndex)
}, 2000);
window._setTimeout = _setTimeout;
window._setInterval = _setInterval;
window._clearTimeout = _clearTimeout;
window._clearInterval = _clearInterval;
})();
I was able to call my callback function at minimum of 250ms using audio tag and handling its ontimeupdate event. Its called 3-4 times in a second. Its better than one second lagging setTimeout
There is a workaround for this problem, although actually the tab must be made active in some window.
Make your inactive tab a separate browser window.
Don't make any other window maximized (unless the maximized window is behind yours).
This should give the browser the impression of always being active.
This is bit cumbersome, but also a quick win. Provided one has control over windows arrangement.
I have a gif image that I want to stretch by making the height and/or width variable. However, I want the image stretching to be done at a speed I set, so it is progressive and visible as it occurs on the screen. The code below works, but it renders the image immediately as a complete image, with no stretching visible. So I thought: insert some kind of timer function to slow down the execution of the "stretching" code. I have tried setTimeout and setInterval (using 1/100 sec delays), but I have not been able to make either work. What am I doing wrong here guys?
$(window).load(function(){
setInterval(function(){
var i=1;
for (i;i<400;i++) {
$("#shape1").html('<img src="image.gif" width="'+i+'" height="40">');
}
},10);
});
The problems with your code are that
at each interval iteration, you repeat the whole for loop
you never stop the interval looping
You may fix your existing code like this :
var i=1;
function step() {
$("#shape1").html('<img src="image.gif" width="'+i+'" height="40">');
if (i++<400) setTimeout(step, 10);
}
step();
Instead of replacing the #shape1 content each time, you could also simply change the width :
var i=1;
var $img = $('<img src="image.gif" width=1 height="40">').appendTo('#shape1');
function step() {
$img.css('width', i);
if (i++<400) setTimeout(step, 10);
}
step();
Demonstration
But jQuery has a very convenient animate function just for this kind of things.
As Dystroy suggested. Use jQuery animate instead
setInterval(function(){
var i=1;
for (i;i<400;i++) {
$("#shape1").animate({
width : i
},10);
}
}, 10);
Here is a jsfiddle
CSS3 transitions are great if your browser supports it.
.resize {
width: 200px;
height: 50px;
transition: width 1s ease;
}
Just add the class to an element to make it stretch out.
img.className = "resize";
css demo
I'm having trouble with a concept with a HTML5/jQuery slideshow system...
I want the images to constantly rotate, without stopping. The way I have it set up now is just going to the first image by changing the margin-left back to 0 when I run out of slides. I'd much rather have it continue indefinitely.
While I'm at it...Is there a way to read a property from the stylesheet? It'd be better if I could ask a user to point the script to the stylesheet and pull the sizing and stuff from there.
Demo: http://bearce.me/so/slideshow
Script (mainly focus on the CSS version, I can convert it to the jQuery version once I understand how to do it):
// JavaScript Document
var slides = 4; // number of slides
var time = 3; // time per slide (in seconds)
var width = 600; // width of slideshow (ex: 600)
var transition = .5 // transition time (in seconds) (for older browsers only, edit css for newer)
window.onload = function start() {
if(Modernizr.csstransitions) {
cssslide();
} else {
jqueryslide();
}
}
function cssslide() {
document.getElementById("container").style.width=(width * slides) + "px";
var num = 0;
setInterval(function() {
num = (num + 1) % slides;
document.getElementById('container').style.marginLeft = (("-" + width) * num) + "px";
}, time * 1000);
}
function jqueryslide() {
$("#container").width((width * slides) + 'px');
var num = 0;
setInterval(function() {
num = (num + 1) % slides;
$("#container").animate({marginLeft: (("-" + width) * num) + "px"},{duration: (transition * 1000)});
}, time * 1000);
}
EDIT: To clarify, I don't want it to constantly scroll, I want it to scroll, stop for a few seconds, scroll, stop, scroll, stop like it does, but instead of zooming all the way back to the first image, I just want it to keep going.
When your slideshow initializes, use JS to duplicate your first image so that the markup looks like this:
<div id="container">
<img src="setup/slides/portal2.jpg" />
<img src="setup/slides/crysis2.jpg" />
<img src="setup/slides/deadspace2.jpg" />
<img src="setup/slides/acb.jpg" />
<img src="setup/slides/portal2.jpg" />
</div>
Then once the 5th slide (duplicate of slide 1) is visible, clear your interval, reset your margin to 0 and re-initialize your slideshow.
I would seriously rethink your approach. Just tacking on more DOM elements into infinity is seriously inefficient, and would probably be an accessibility nightmare.
I would suggest you check out the jQuery Cycle plugin - it's real easy to implement, and allows you to loop infinitely.