how to keep loading screen for more than 4 seconds? - javascript

I am trying to keep the loading screen for at least 4 seconds. But the timer at the end isn't working here's the code
window.addEventListener("load", () => {
const preload = document.querySelector('.preload');
preload.classList.add('preload-finish');
}, 4000);

Use setTimeout
window.addEventListener("load", () => {
const preload = document.querySelector('.preload');
setTimeout(()=>{preload.classList.add('preload-finish')}, 4000)
});

your 2nd parameter is a true or false for bubble/capture
use setTimeout instead
function fName(){
...do something;
}
document.setTimeout(function_name(), 4000)

Related

Why isn't my Javascript function continuously firing with setTimeout/clearTimeout?

I have a webpage i'm working on with a carousel of sorts which auto rotates between 4 products/images. But it also has a hover feature which needs to stop the auto rotate and display just the product a user hovers on, and auto rotate resumes off hover. I have it working for the most part. The hover functionality is working as intended, problem is the auto rotate only cycles through one time. Why doesn't it keep cycling through despite my setTimeout function for autoRotate() calling itself again?
Relevant JS code with some edits for brevity and what not:
// Run autoRotate() on page load
$(document).ready(function () {
autoRotate();
});
// Place timeout functions for each product's function into
// a variable so the timeout can be cleared on hover
let product2Timer = setTimeout(setProduct2, 3000);
let product3Timer = setTimeout(setProduct3, 6000);
let product4Timer = setTimeout(setProduct4, 9000);
let autoRotateTimer = setTimeout(autoRotate, 12000);
// Main function
function autoRotate() {
setProduct1();
product2Timer ;
product3Timer ;
product4Timer ;
autoRotateTimer; // <--- This should call autoRotate() again (but it doesn't)?
}
// On product name hover, clear the timeouts so the rotator doesnt keep cycling on hover
// Off product name hover, reset timeouts and resume/call autoRotate() function
$(function () {
$(".rotator-item").hover(function () {
clearTimeout(product2Timer);
clearTimeout(product3Timer);
clearTimeout(product4Timer);
clearTimeout(autoRotateTimer);
},
function () {
product2Timer = setTimeout(setProduct2, 3000);
product3Timer = setTimeout(setProduct3, 6000);
product4Timer = setTimeout(setProduct4, 9000);
autoRotateTimer = setTimeout(autoRotate, 12000);
autoRotate();
});
});
function setProduct1() {
// Set product info/img/description etc...
}
function setProduct2() {
// Set product info/img/description etc...
}
function setProduct3() {
// Set product info/img/description etc...
}
function setProduct4() {
// Set product info/img/description etc...
}
//
// On hover styling/code
//
$(function () {
$(".product-1").hover(function () {
// Mouse over code
},
function () {
// Mouse out code...
});
});
// Other 3 product hover functions...
Thanks!
Use setInterval() to start a repeating action. Use setTimeout() to stagger their start times.
var interval1, interval2, interval3, interval4;
function startRotation() {
setTimeout(function() {
interval1 = setInterval(setProduct1, 12000);
}, 3000);
setTimeout(function() {
interval2 = setInterval(setProduct2, 12000);
}, 6000);
setTimeout(function() {
interval3 = setInterval(setProduct3, 12000);
}, 9000);
setTimeout(function() {
interval4 = setInterval(setProduct4, 12000);
}, 12000);
};
startRotation();
The hover handler can then clear all 4 interval timers, and then call startRotation() to start them again.

On mouse over enable button after 3 seconds, on mouse off disable and stop count down

I have a button that does something irreversible and I'm trying to put a lockout on it unless the user hovers over it for 3 seconds. If they wait 3 seconds the button becomes enabled. As soon as they mouse off it disables again. If they also mouse off during the count down of 3 seconds it stops the count down.
$('#delete_btn').on('mouseover', function () {
setTimeout(function () {
$('#delete_btn').prop('disabled', false)
}, 3000)
})
$('#delete_btn').on('mouseout', function () {
$('#delete_btn').prop('disabled', true)
})
I'm not sure how to stop the count down if they mouse out early
You need to clear the timeout. So, it's ready to fire on the next call:
var timeout;
$('#delete_btn').on('mouseover', function() {
timeout = setTimeout(function() {
$('#delete_btn').prop('disabled', false);
}, 3000);
});
$('#delete_btn').on('mouseout', function() {
clearTimeout(timeout);
$('#delete_btn').prop('disabled', true);
});
See it in work at CodePen:
https://codepen.io/aminshahrokhi/pen/VNJBYZ
this a copy-paste from W3School, basiclly you have to 'save' the timeout into a var, an then, on hover, clear the time out:
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
I hope this helps :)

Function setIntervall become faster after change router

https://protected-temple-97157.herokuapp.com/
here theres my app, if you open you see that there no problems on slideshow, the image change after the 6 seconds, but if you go to other router and then comeback on Home after the first image the slideshow become more faster
componentDidMount() {
this.slide();
}
slide = () => {
$(".slideshow > .card:gt(0)").hide();
setInterval(() => {
$(".slideshow > .card:first")
.fadeOut(3000)
.next()
.fadeIn(3000)
.end()
.appendTo('.slideshow')
}, 6000)
}
I guess you add a new Interval each time you come back to the site. If you look closely you see that the time difference between the slides varies, therefore multiple intervals are set.
You can prevent this by calling setInterval only once, initially, or use clearInterval to clear the previous interval.
It's not that the slideshow is faster, but you will get another interval that changes slides because you don't stop the previous interval when the component is unmounted.
You can put the number returned from setInterval on the component and call clearInterval in componentWillUnmount to get around this.
Example
class App extends React.Component {
interval = null;
componentDidMount() {
this.slide();
}
componentWillUnmount() {
clearInterval(this.interval);
}
slide = () => {
$(".slideshow > .card:gt(0)").hide();
this.interval = setInterval(() => {
$(".slideshow > .card:first")
.fadeOut(3000)
.next()
.fadeIn(3000)
.end()
.appendTo(".slideshow");
}, 6000);
};
}

setInterval triggers function multiple times

EDIT: what i mean by fires multiple times, is that newjob() will fire 3 times, every 5 seconds...so in 20 seconds i'll have it 12 times triggered, instead of the 4 times that i would want. so it's triggeres multiple times every 5 seconds, instead of once every 5 seconds.
I have a function that i created using Toastr to display a message on my web application. i'm eventually going to tie it to an ajax request to an API to determine whether or not to display a message, but for now i'm just testing how it looks.
i am setting an interval, but it fires the function inside of it multiple times (usually 3).
$(document).ready(function() {
setInterval(function () {
newJob();
}, 5000);
});
i can't do setInterval( function(e) { } as e is undefined, as there is no event associated with it, on click, i've used e.stopImmediatePropagation(); to have it only fire once.
how can i stop this immediate propagation on set interval if i don't have e?
thank you.
EDIT: full code:
var newJob = function(e) {
var i = -1;
var $toastlast;
var getMessage = function () {
var msgs = ["There's a new job in the job dispatch queue", "A job pending approval has timed out"];
i++;
if (i === msgs.length) {
i = 0;
}
return msgs[i];
};
var shortCutFunction = "success"; // 'success' or 'error'
toastr.options = {
closeButton: true,
progressBar: true,
debug: false,
positionClass: 'toast-top-full-width',
onclick: null,
timeOut: "0",
extendedTimeOut: "0",
showDuration: "0",
hideDuration: "0",
showEasing: "swing",
hideEasing: "linear",
showMethod: "fadeIn",
hideMethod: "fadeOut",
};
toastr.options.onclick = function () {
window.location.href = "/dispatcher";
};
var msg = getMessage();
$("#toastrOptions").text("Command: toastr["
+ shortCutFunction
+ "](\""
+ msg
+ "\")\n\ntoastr.options = "
+ JSON.stringify(toastr.options, null, 2)
);
var $toast = toastr[shortCutFunction](msg);
};
$(document).ready(function() {
setInterval(function () {
console.log('set interval');
newJob();
}, 5000);
});
and this is my index.phtml file:
<?php
echo $this->headScript()->appendFile($this->basePath() . '/plugins/toastr/toastr.js')
echo $this->headScript()->appendFile($this->basePath().'/js/dispatchernotification.js');
?>
all i'm doing is adding the javascript of what i want running to my index.phtml file and the toastr library.
by console.loging inside interval, i get three logs.
here's a fiddle..not sure how to run it though as it's on ready
http://jsfiddle.net/efecarranza/rfvbhr1o/
setInterval will continue endlessly. I think you're looking for setTimeout.
Make sure to put your setInterval outside of $(document).ready(function() {...}). So it will be like:
<script>
$(document).ready(function() {
... some code ...
});
var myInterval;
clearInterval(myInterval);
myInterval = setInterval(function() {
... your code is here ...
}, 5000);
</script>
For some reason, if it's within $(document).ready() every time you dynamically bring the same page again it double-sets the setInterval in progression and clearInterval function doesn't help until you actually refresh the browser.
setInterval: call a function repeatedly every x milliseconds
setTimeOut: call a function after x milliseconds.
You have two options:
Clear the interval when it isn't necessary anymore:
var intervalId;
$(document).ready(function() {
intervalId = setInterval(function () {
newJob();
}, 5000);
});
// At some other point
clearInterval(intervalId);
Or, the simpler solution in your case, use setTimeout:
$(document).ready(function() {
setTimeout(function () {
newJob();
}, 5000);
});
It would help if you can add a jsfiddle with your code so we can see what's going wrong exactly. It's possible that for whatever reason the setInterval function is being called multiple times. Try adding a console.log statement at the start of that function to check if that's the case.
If it is and you can't figure out why (and neither can we without knowing your code), you could place a check at the start of the function like this:
if (typeof this.installInterval.done == "undefined") {
/*a bunch of code*/
this.installInterval.done = true
}
May be by mistake you are calling your script twice as I did!
In the code below I have called 'testLoop.js' two times.
<script src="../js/testLoop.js"></script>
<script type="text/javascript" src="../js/testLoop.js"></script>
<script type="text/javascript" src="../js/cube.js"></script>

how to play a sound file after another sound in javascript

How do I play a sound file after another sound ends? If I do it like
first.play();
second.play();
Both the sounds play at the same time. I want to play first.play() and when it ends, starts second.play().
first.addEventListener('ended', function(){
second.play();
});
first.play();
I would recommend kind of something:
// if using jQuery:
var audios = $('audio');
audios.each(function(idx){
$(this).bind('ended', function(){
var next = audios.get(idx+1);
if(next){
next.get(0).play();
}
});
});
You can also use a promise with a timeout:
const playPromise = first.play()
playPromise.then(() => {
setTimeout(() => {second.play()}, first.duration * 1000)
})
I used the AudioScheduledSourceNode.onended.
I used four sounds, and put this code in a function:
sound1.play();
sound1.onended = function () {
sound2.play();
};
sound2.onended = function () {
sound3.play();
};
sound3.onended = function () {
sound4.play();
}
Here is the app live: insultinator-toy.netlify.app
Click the question mark button.
And the link to the ugly source code. jsahlsa

Categories