Large numbers in count-up show NaN in safari browser - javascript

I have created a count-up function in Vanilla JS. Everything works well. The counter starts when you scroll down to it. Unfortunately the big number 35 000 000 shows up as NaN in the iOS Safari browser. I have no idea why. Please help. It looks like large numbers don't work in iOS Safari browser.
var animationDuration = 3000;
var frameDuration = 1000 / 60;
var totalFrames = Math.round(animationDuration / frameDuration);
var easeOutQuad = t => t * (2 - t);
var animateCountUp = el => {
let frame = 0;
var countTo = parseInt(el.innerHTML.replace(/ /g, ''), 10);
var counter = setInterval(() => {
frame++;
var progress = easeOutQuad(frame / totalFrames);
var currentCount = Math.round(countTo * progress);
if (parseInt(el.innerHTML, 10) !== currentCount) {
el.textContent = currentCount.toLocaleString().replace(/,/g, ' ');
}
if (frame === totalFrames) {
clearInterval(counter);
}
}, frameDuration);
};
var count = document.querySelectorAll('.countup'),
once = 1;
document.addEventListener('scroll', function() {
if (once == 1 && count[0].getBoundingClientRect().top < window.innerHeight) {
once = 0;
count.forEach(animateCountUp);
}
});
<div style="position: fixed">
<span class="countup">12 500</span>
<span class="countup">35 000 000</span>
</div>
<div style="height: 5000px"></div>

Using innerHTML for this is slightly less than ideal, and in fact iOS Safari is adding markup to your large number which is tripping up your code. It's identifying it as a telephone number and changing the inner HTML of that element to: 35 000 000. That's very surprising, but you can see it here:
console.log(document.querySelector(".countup").innerHTML);
<span class="countup">35 000 000</span>
Note: Only on iOS Safari as far as I can tell.
Using textContent instead works, since the text is unchanged:
var animationDuration = 3000;
var frameDuration = 1000 / 60;
var totalFrames = Math.round(animationDuration / frameDuration);
var easeOutQuad = t => t * (2 - t);
var animateCountUp = el => {
let frame = 0;
var countTo = parseInt(el.textContent.replace(/ /g, ''), 10);
var counter = setInterval(() => {
frame++;
var progress = easeOutQuad(frame / totalFrames);
var currentCount = Math.round(countTo * progress);
if (parseInt(el.textContent, 10) !== currentCount) {
el.textContent = currentCount.toLocaleString().replace(/,/g, ' ');
}
if (frame === totalFrames) {
clearInterval(counter);
}
}, frameDuration);
};
var count = document.querySelectorAll('.countup'),
once = 1;
document.addEventListener('scroll', function() {
if (once == 1 && count[0].getBoundingClientRect().top < window.innerHeight) {
once = 0;
count.forEach(animateCountUp);
}
});
<div style="position: fixed">
<span class="countup">12 500</span>
<span class="countup">35 000 000</span>
</div>
<div style="height: 5000px"></div>
You can also tell iOS Safari not to do this by adding a meta tag as described in this question's answers:
<meta name="format-detection" content="telephone=no">
but as far as I can tell that disables it page-wide.

Why not use counto instead of using DOM as a storage for the number to counto?
And as TJ said, the issue was Safari's handling of your number when using innerHTML instead of textContent
if (currentCount<=countTo) {
el.textContent = currentCount.toLocaleString().replace(/,/g, ' ');
}
Tested on iOS 14.4
https://plungjan.name/SO/tl.html
var animationDuration = 3000;
var frameDuration = 1000 / 60;
var totalFrames = Math.round(animationDuration / frameDuration);
var easeOutQuad = t => t * (2 - t);
var animateCountUp = el => {
let frame = 0;
var countTo = parseInt(el.textContent.replace(/ /g, ''), 10); // do not use innerHTML here
var counter = setInterval(() => {
frame++;
var progress = easeOutQuad(frame / totalFrames);
var currentCount = Math.round(countTo * progress);
if (currentCount<=countTo) {
el.textContent = currentCount.toLocaleString().replace(/,/g, ' ');
}
if (frame === totalFrames) {
clearInterval(counter);
}
}, frameDuration);
};
var count = document.querySelectorAll('.countup'),
once = 1;
document.addEventListener('scroll', function() {
if (once == 1 && count[0].getBoundingClientRect().top < window.innerHeight) {
once = 0;
count.forEach(animateCountUp);
}
});
<div style="position: fixed">
<span class="countup">12 500</span>
<span class="countup">35 000 000</span>
</div>
<div style="height: 5000px"></div>

Related

How can I get this timer script to function within a html/js element in ClickFunnels?

I've been trying to figure out how to get this to work in a single HTML/JS element in ClickFunnels.
I need to use a div tag instead of body tag but unfortunately I cannot use onLoad with divs as I've recently discovered.
I would highly appreciate any help on this as I've already spent a few hours trying to figure this out.
Here is the HTML
<body onLoad="startCount();">
<span class="timerz">Spots remaining: <span id="counterz">19</span></span>
</body>
Here is the JS
<script>
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var rand_no = Math.ceil(3 * Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById("counterz");
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 0) {
el.innerHTML = newNumber;
} else {
el.innerHTML = "1"; // This message is displayed when the counter reaches zero.
}
}
</script>
<script>
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var rand_no = Math.ceil(3 * Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById("counterz");
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 0) {
el.innerHTML = newNumber;
} else {
el.innerHTML = "1"; // This message is displayed when the counter reaches zero.
}
}
document.addEventListener("DOMContentLoaded", (event) => {
startCount();
});

Can you set a minimum time a script will run for?

Is it possible to add a minimum time my script will run for? It's a preloader, and sometimes the script runs longer than other times. I don't want to set a delay because if the site takes 20 minutes to load, adding an extra 10 seconds to it is just way too much loading time. Can I set this script so it has to run for a minimum of say 5 seconds?
var rafId = null,
delay = 200,
lTime = 0;
function scroll() {
var e = $(window).scrollTop(),
a = $(window).height(),
n = e + a;
$(".reveal").each(function () {
var a = $(this);
if (!a.hasClass("reveal_visible")) {
var l = a.offset().top;
l <= n && (l + a.height() < e ? a.removeClass("reveal_pending").addClass("reveal_visible") : (a.addClass("reveal_pending"), rafId || requestAnimationFrame(reveal)))
$( "#someID" ).addClass( "someAnimationClass" );
}
})
}
function reveal() {
rafId = null;
var e = performance.now();
if (e - lTime > delay) {
lTime = e;
var a = $(".reveal_pending");
$(a.get(0)).removeClass("reveal_pending").addClass("reveal_visible")
}
$(".reveal_pending").length >= 1 && (rafId = requestAnimationFrame(reveal))
}
$(window).load(function () {
$(".se-pre-con").delay(0).fadeOut("slow", function () {
scroll(), $(window).scroll(scroll)
})
});

I use window.scrollBy() for smooth scroll but it doesn't work for Safari [duplicate]

As the title says, it works perfectly fine on Chrome. But in Safari, it just sets the page to the desired top and and left position. Is this the expected behaviour? Is there a way to make it work nicely?
Use smoothscroll polyfill (solution for all browsers), easy applicable and lightweight dependency:
https://github.com/iamdustan/smoothscroll
Once you install it via npm or yarn, add it to your main .js, .ts file (one which executes first)
import smoothscroll from 'smoothscroll-polyfill';
// or if linting/typescript complains
import * as smoothscroll from 'smoothscroll-polyfill';
// kick off the polyfill!
smoothscroll.polyfill();
Behavior options aren't fully supported in IE/Edge/Safari, so you'd have to implement something on your own. I believe jQuery has something already, but if you're not using jQuery, here's a pure JavaScript implementation:
function SmoothVerticalScrolling(e, time, where) {
var eTop = e.getBoundingClientRect().top;
var eAmt = eTop / 100;
var curTime = 0;
while (curTime <= time) {
window.setTimeout(SVS_B, curTime, eAmt, where);
curTime += time / 100;
}
}
function SVS_B(eAmt, where) {
if(where == "center" || where == "")
window.scrollBy(0, eAmt / 2);
if (where == "top")
window.scrollBy(0, eAmt);
}
And if you need horizontal scrolling:
function SmoothHorizontalScrolling(e, time, amount, start) {
var eAmt = amount / 100;
var curTime = 0;
var scrollCounter = 0;
while (curTime <= time) {
window.setTimeout(SHS_B, curTime, e, scrollCounter, eAmt, start);
curTime += time / 100;
scrollCounter++;
}
}
function SHS_B(e, sc, eAmt, start) {
e.scrollLeft = (eAmt * sc) + start;
}
And an example call is:
SmoothVerticalScrolling(myelement, 275, "center");
For a more comprehensive list of methods for smooth scrolling, see my answer here.
window.requestAnimationFrame can be used to perform smooth scrolling in an exact amount of time.
For smooth vertical scrolling, the following function can be used. Note that horizontal scrolling can be done in much the same manner.
/*
#param time: the exact amount of time the scrolling will take (in milliseconds)
#param pos: the y-position to scroll to (in pixels)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
Demo:
/*
#param time: the exact amount of time the scrolling will take (in milliseconds)
#param pos: the y-position to scroll to (in pixels)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
document.querySelector('button').addEventListener('click', function(e){
scrollToSmoothly(500, 1500);
});
html, body {
height: 1000px;
}
<button>Scroll to y-position 500px in 1500ms</button>
For more complex cases, the SmoothScroll.js library can be used, which handles smooth scrolling both vertically and horizontally, scrolling inside other container elements, different easing behaviors, scrolling relatively from the current position, and more. It also supports most browsers that do not have native smooth scrolling.
var easings = document.getElementById("easings");
for(var key in smoothScroll.easing){
if(smoothScroll.easing.hasOwnProperty(key)){
var option = document.createElement('option');
option.text = option.value = key;
easings.add(option);
}
}
document.getElementById('to-bottom').addEventListener('click', function(e){
smoothScroll({yPos: 'end', easing: easings.value, duration: 2000});
});
document.getElementById('to-top').addEventListener('click', function(e){
smoothScroll({yPos: 'start', easing: easings.value, duration: 2000});
});
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll#1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<!-- Taken from one of the library examples -->
Easing: <select id="easings"></select>
<button id="to-bottom">Scroll To Bottom</button>
<br>
<button id="to-top" style="margin-top: 5000px;">Scroll To Top</button>
The workarounds above all make up for the lack of Safari support for behaviors.
It's still necessary to detect when a workaround is needed.
This little function will detect if smooth scrolling is supported by the browser. It returns false on Safari, true on Chrome and Firefox:
// returns true if browser supports smooth scrolling
const supportsSmoothScrolling = () => {
const body = document.body;
const scrollSave = body.style.scrollBehavior;
body.style.scrollBehavior = 'smooth';
const hasSmooth = getComputedStyle(body).scrollBehavior === 'smooth';
body.style.scrollBehavior = scrollSave;
return hasSmooth;
};
const pre = document.querySelector('pre');
// returns true if browser supports smooth scrolling
const supportsSmoothScrolling = () => {
const body = document.body;
const scrollSave = body.style.scrollBehavior;
body.style.scrollBehavior = 'smooth';
const hasSmooth = getComputedStyle(body).scrollBehavior === 'smooth';
body.style.scrollBehavior = scrollSave;
return hasSmooth;
};
const supported = supportsSmoothScrolling();
pre.innerHTML = `supported: ${ (supported) ? 'true' : 'false'}`;
<h3>
Testing if 'scrollBehavior smooth' is supported
</h3>
<pre></pre>
Update
Test of Safari Technology Preview, Release 139 (Safari 15.4) shows support for scrollBehavior smooth, so we may expect to see support in 15.4.
The solution with the smoothest performance, especially if you want to incorporate easing is to use requestAnimationFrame:
const requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
const step = (timestamp) => {
window.scrollBy(
0,
1, // or whatever INTEGER you want (this controls the speed)
);
requestAnimationFrame(step);
};
requestAnimationFrame(step);
if you want to later cancel the scroll, you need to have a reference to your requestAnimationFrame (do this everywhere you use requestAnimationFrame(step)):
this.myRequestAnimationFrame = requestAnimationFrame(step);
const cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
cancelAnimationFrame(this.myRequestAnimationFrame);
Now what if you want to use easing with your scroll and take timeouts between scroll actions?
create an array of 60 elements (requestAnimationFrame usually calls 60 times per second. It's technically whatever the refresh rate of the browser is, but 60 is the most common number.) We are going to fill this array non-linearly then use those numbers to control how much to scroll at each step of requestAnimationFrame:
let easingPoints = new Array(60).fill(0)
choose an easing function. Let's say we're doing a cubic ease-out:
function easeCubicOut(t) {
return --t * t * t + 1;
}
create a dummy array and fill it with data piped through the easing function. You'll see why we need this in a moment:
// easing function will take care of decrementing t at each call (too lazy to test it at the moment. If it doesn't, just pass it a decrementing value at each call)
let t = 60;
const dummyPoints = new Array(60).fill(0).map(()=> easeCubicOut(t));
const dummyPointsSum = dummyPoints.reduce((a, el) => {
a += el;
return a;
}, 0);
map easingPoints using the help of each dummyPoint ratio to dummyPointsSum:
easingPoints = easingPoints.map((el, i) => {
return Math.round(MY_SCROLL_DISTANCE * dummyPoints[i] / dummyPointsSum);
});
in your scroll function, we'll make a few adjustments:
const requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
let i = 0;
const step = (timestamp) => {
window.scrollBy(
0,
easingPoints[i],
);
if (++i === 60) {
i = 0;
return setTimeout(() => {
this.myRequestAnimationFrame = requestAnimationFrame(step);
}, YOUR_TIMEOUT_HERE);
}
};
this.myRequestAnimationFrame = requestAnimationFrame(step);
A simple jQuery fix that works for Safari:
$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function (t) {
if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
var e = $(this.hash);
e = e.length ? e : $("[name=" + this.hash.slice(1) + "]"), e.length && (t.preventDefault(), $("html, body").animate({
scrollTop: e.offset().top
}, 600, function () {
var t = $(e);
if (t.focus(), t.is(":focus")) return !1;
t.attr("tabindex", "-1"), t.focus()
}))
}
});
Combining the answers of George Daniel and terrymorse, the following can be used for all the browser's support using native JavaScript.
As, Chrome, Firefox supports CSS, scroll-behavior: smooth; for the browsers which don't support this property, we can add below.
HTML:
<a onclick="scrollToSection(event)" href="#section">
Redirect On section
</a>
<section id="section">
Section Content
</section>
CSS:
body {
scroll-behavior: smooth;
}
JavaScript:
function scrollToSection(event) {
if (supportsSmoothScrolling()) {
return;
}
event.preventDefault();
const scrollToElem = document.getElementById("section");
SmoothVerticalScrolling(scrollToElem, 300, "top");
}
function supportsSmoothScrolling() {
const body = document.body;
const scrollSave = body.style.scrollBehavior;
body.style.scrollBehavior = 'smooth';
const hasSmooth = getComputedStyle(body).scrollBehavior === 'smooth';
body.style.scrollBehavior = scrollSave;
return hasSmooth;
};
function SmoothVerticalScrolling(element, time, position) {
var eTop = element.getBoundingClientRect().top;
var eAmt = eTop / 100;
var curTime = 0;
while (curTime <= time) {
window.setTimeout(SVS_B, curTime, eAmt, position);
curTime += time / 100;
}
}
function SVS_B(eAmt, position) {
if (position == "center" || position == "")
window.scrollBy(0, eAmt / 2);
if (position == "top")
window.scrollBy(0, eAmt);
}
Another possible solution with an "ease-out" effect.
Inspired by some of the answers given earlier,
a key difference is in using "pace" instead of specifying a duration, I found that calculating the length of each step based on a fixed pace creates a smooth "ease-out" effect as the number of steps increases as the scroll approaches the destination point.
Hopefully the code below is easy to understand.
function smoothScrollTo(destination) {
//check if browser supports smooth scroll
if (window.CSS.supports('scroll-behavior', 'smooth')) {
window.scrollTo({ top: destination, behavior: 'smooth' });
} else {
const pace = 200;
let prevTimestamp = performance.now();
let currentPos = window.scrollY;
// #param: timestamp is a "DOMHightResTimeStamp", check on MDN
function step(timestamp) {
let remainingDistance = currentPos < destination ? destination - currentPos : currentPos - destination;
let stepDuration = timestamp - prevTimestamp;
let numOfSteps = pace / stepDuration;
let stepLength = remainingDistance / numOfSteps;
currentPos = currentPos < destination ? currentPos + stepLength : currentPos - stepLength;
window.scrollTo({ top: currentPos });
prevTimestamp = timestamp;
if (Math.floor(remainingDistance) >= 1) window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
}
This is my first contribution on SO after years of benefiting from this great community. Constructive criticism is highly appreciated.
Thanks to T.Dayya, I had combined few answers on that topic and here is ts module with
extension function scrollSmoothIntoView.
export default {}
declare global {
interface Element {
scrollSmoothIntoView(): void;
}
}
Element.prototype.scrollSmoothIntoView = function()
{
const t = 45;
const tstep = 6.425/t;
const dummyPoints = new Array(t).fill(0).map((t, i) => circ(i * tstep));
const dummyPointsSum = dummyPoints.reduce((a, el) => { a += el; return a;}, 0);
const _window: any = window;
const _elem: any = getScrollParent(this);
const scroll_distance: any = (this as any).offsetTop - (!_elem.parentElement ? _window.scrollY : 0);
let easingPoints = new Array(t).fill(0)
easingPoints = easingPoints.map((el, i) => {
return Math.round(scroll_distance * dummyPoints[i] / dummyPointsSum);
});
const requestAnimationFrame = _window.requestAnimationFrame ||
_window.mozRequestAnimationFrame ||
_window.webkitRequestAnimationFrame ||
_window.msRequestAnimationFrame;
let i = 0;
const step = (timestamp:any) => {
_elem.scrollBy(0, easingPoints[i]);
if (++i < t)
setTimeout(() => { requestAnimationFrame(step) }, 2);
};
window.requestAnimationFrame(()=>requestAnimationFrame(step));
}
function getScrollParent(element: any, includeHidden?: any):any {
var style = getComputedStyle(element);
var excludeStaticParent = style.position === "absolute";
var overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/;
if (style.position === "fixed") return document.body;
for (var parent = element; (parent = parent.parentElement);) {
style = getComputedStyle(parent);
if (excludeStaticParent && style.position === "static") {
continue;
}
if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX)) return parent;
}
return document.body;
}
function circ(t:any) {
return 1+Math.cos(3+t);
}
Using html_element.scrollSmoothIntoView().

Javascript random countdown - how to repeat same time multiple times on same page

I have a random countdown script, as per below:
Here is the Javascript:
<script>
var timer;
function startCount()
{
timer = setInterval(count, 1000); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count()
{
var do_wait = Math.ceil(4*Math.random());
if (do_wait == 4) {
var rand_no = Math.ceil(4*Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 3) {
el.innerHTML = newNumber;
} else {
el.innerHTML = '<font color="white">3</font>'; // This message is displayed when the counter reaches zero.
}
}
}
startCount();
</script>
Here is how I am calling it in HTML
<span style="color:white;" id="counter">50</span>
I want to be able to display the ID "counter" multiple times on the page with the same countdown number. The problem is each time I display ID "counter" it has a different countdown number.
I'd change 'id' for 'name' so I do not have the same id multiple times in my document. I've made a few changes in your code:
<html>
<head>
<script>
var timer;
function startCount()
{
timer = setInterval(count, 1000); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count()
{
var do_wait = Math.ceil(4*Math.random());
if (do_wait == 4) {
var rand_no = Math.ceil(4*Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var els = document.getElementsByName('counter');
for(var i = 0 ; i < els.length ; i++) {
var currentNumber = parseFloat(els[i].innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 3) {
els[i].innerHTML = newNumber;
} else {
els[i].innerHTML = '<font color="white">3</font>'; // This message is displayed when the counter reaches zero.
}
}
}
}
startCount();
</script>
</head>
<body>
<span style="color:white;" name="counter">50</span>
<span style="color:white;" name="counter">50</span>
<span style="color:white;" name="counter">50</span>
<span style="color:white;" name="counter">50</span>
</body>
I'm now using counter as values for name attributes and document.getElementsByName() to read those array of names.
BTW, I tested in Chrome.

DHTML - Show picture for limited time

im try to use DHTML in order to make animation for 3-5 sec( the anumation supose to start from the left to the right...).
any idea how to do tthat???
//this one will set the the pictue on the right side of the screen
function setUpPicture() {
subRunnerOBJ = new Object();
subRunnerOBJ.topPos = 100;
subRunnerOBJ.leftPos = 0;
subRunnerOBJ.velX = 400;
subRunnerOBJ.velY = 0;
subRunnerOBJ.score = 0;
hide1.style.visibility = "visible";
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
hide1.style.position = "absolute";
//once we place the location of the sub , we will Call to new function that will move it
startMovePicture();
}
function startMovePicture() {
dt = 50; // in miliseconds
h = setInterval("moveObj(subRunnerOBJ)", dt);
}
function moveObj(someObj) {
counter = 0;
while (counter < 30000) {
subRunnerOBJ.leftPos = subRunnerOBJ.leftPos + subRunnerOBJ.velX * dt / 1000;
subRunnerOBJ.topPos = subRunnerOBJ.topPos + subRunnerOBJ.velY * dt / 1000;
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
counter = counter + 50;
if (counter == 3000) {
stopRunning();
}
}
}
function stopRunning() {
clearInterval(h);
hide1.style.visibility = "hidden";
}
with this function i can see the picture for less than a sec...
how can i set the time here??
Replace the milliseconds value with a number equal to the desired number of seconds, which would be 5000 for five seconds. Remove the while loop inside of moveObj and replace it by adding clearInterval(h) and hide1.style.visibility = "hidden"; as the last statement inside that block.

Categories