I want to create an marquee that start at first, but every 10 seconds, the marquee will stop for 5 seconds before the marquee start again.
How can I do that?
I only manage to create a timer that stop the marquee after 5 seconds :
<script>
function startLoop() {
setInterval( "doSomething()", 5000 ); }
function doSomething() {
document.getElementById('myMarquee').stop(); }
</script>
HTML
<body onload="startLoop();">
<marquee direction="right" id="myMarquee">This is a marquee.</marquee>
</body>
A few days ago I needed something similar to your problem. I soon figured out that marquee is not a standard element, so you can't use it in cross-browser solutions.
I have extracted the animation part, based on jQuery, I used in my solution, you can see the effect in this jsFiddle
HTML
<div id="container">
<div id="mytext">
this is a simple text to test custom marquee
</div>
</div>
CSS
#container
{
display: inline-block;
background-color: #cccccc;
width: 100px;
height: 100px;
overflow: hidden;
}
#mytext
{
display: inline-block;
position: relative;
white-space: nowrap;
}
JavaScript
$(function() {
var txt = $("#mytext");
txt.bind('scroll', function () {
var el = $(this);
// Scroll state machine
var scrollState = el.data("scrollState") || 0;
el.data("scrollState", (scrollState + 1) % 4);
switch (scrollState) {
case 0: // initial wait
el.css({ left: 0 });
el.show();
window.setTimeout(function () {
el.trigger("scroll");
}, 5000);
break;
case 1: // start scroll
var delta = el.parent().width() - el.width();
if (delta < 0) {
el.animate({ left: delta }, 2000, "linear", function () {
el.trigger("scroll");
});
}
break;
case 2: // delay before fade out
window.setTimeout(function () {
el.trigger("scroll");
}, 2000);
break;
case 3: // fade out
el.fadeOut("slow", function () {
el.trigger("scroll");
});
break;
}
}).trigger("scroll");
});
It doesn't do exaclty the same as your requirement, but if you read the code and make some changes to the state-machine, you will get it working :)
If you want to keep using the marquee, this should work (In browsers that support the marquee):
<script>
function stopRunning() {
document.getElementById('myMarquee').stop();
setInterval("startRunning()", 5000);
}
function startRunning() {
document.getElementById('myMarquee').start();
setInterval("stopRunning()", 10000);
}
//You don't really need a function to start the loop, you can just call startRunning();
startRunning();
</script>
This will make the marquee start running, stop after 10 seconds, start again after 5, and repeat.
try this:
var myMarquee = document.getElementById('myMarquee');
run();
function run() {
setTimeout(function() {
myMarquee.stop();
setTimeout(function(){
myMarquee.start();
run();
},5000);
},10000);
}
see it run at http://jsfiddle.net/gjwYh/
To implement every 10 seconds, the marquee will stop for 5 seconds before the marquee start again You need some logic like. I have used step variable to control the progress. Hope its clear
<script>
var step = 1; // marquee is run on load time
function startLoop()
{
setInterval("doSomething()", 5000 );
}
function doSomething()
{
if (step == 0) {
// 5 seconds are passed since marquee stopped
document.getElementById('myMarquee').start();
step = 1;
}
else
{
if (step == 1) {
// 5 seconds are passed since marquee started
step = 2; // Just delay of another 5 seconds before stop
}
else
{
if (step == 2) {
// 10 seconds are passed since marquee started
document.getElementById('myMarquee').stop();
step = 0;
}
}
}
}
</script>
Check Out its Working Here on Jsfiddle. I have also added a timer in a div which will give you ease in checking the behavior of stop and start against time
if you want to apply same in angular then you do like this
import { Component, OnInit , ElementRef, ViewChild} from '#angular/core';
write this under class
#ViewChild('myname', {static: false}) myname:ElementRef;
to start the loop write this under ngOnInit
setTimeout(()=>{ //<<<--- using ()=> syntax
this.startRunning()
console.log("aaa")
}, 1000);
place this code outside of ngOnInit
startRunning() {
setInterval(() =>{
this.myname.nativeElement.stop();
setTimeout(() =>{
this.myname.nativeElement.start();
console.log("start")
},2000)
console.log("stop")
}, 4000);
}
Related
when coding, I came upon this very weird problem. My code is below:
js
document.getElementById("id").style.width = "0%"
var a = 0;
setTimeout(function () {
if (a <= 60) {
document.getElementById("id").style.width = a + "%";
a++;
}
}, 100);
I want it to run 60 times, each time changing the div's width by 1%
However, when I run the code, the if block makes it finish instantly as if the timeout didn't work. Can anyone tell me what's wrong? Thanks in advance!
setTimeout function executes only once after that specified time in milli seconds.
If you want to keep on executing the block, you have to make use of setInterval instead of setTimeout.
setInterval keeps on calling the function since the interval is cleared.
Dont forget to call clearInterval once target achieved.
var a = 0;
const interval = setInterval(function () {
if (a <= 60) {
console.log("Im being called");
document.getElementById("id").style.width = a + "%";
a++;
} else {
// Target achieved, clearing interval
console.log("Im stoping execution");
clearInterval(interval)
}
}, 100);
#id {
height: 300px;
background: orange;
}
<div id="id"></div>
I have an HTML page that has timeouts. I want to freeze them when you press a button (#pauseButton) and then resume when you press it again, preferably freezing all BS4 and jQuery animations also.
<button id="pauseButton"></button>
<script>
$(document).ready(function(){
setTimeout(function() {
alert("This is an alert")
},10000);
$("#pauseButton").click(function(){
// Pause timeouts and page
});
});
</script>
EDIT
I have been notified that there is a possible duplicate answer, so I am now focusing on pausing animations and other page elements.
That answer shows how to pause timeouts only.
There are many ways to solve this issue. Many of them are mentioned in this question as mentioned by #EmadZamout in the comments.
But, if you are looking for an easy and maybe an alternate way to solve this. Try this. Here I am using requestAnimationFrame to solve the issue
let ran = Date.now(); // contains the last updated time
let time = 0; // time in seconds
let paused = false; // store the state
const func = () => {
if (!paused && Date.now() - ran > 1000) {
time++;
ran = Date.now();
console.log('now')
}
if (time === 8)
return alert('This works!');
requestAnimationFrame(func);
}
func();
document.querySelector('button').addEventListener('click', () => paused = !paused);
<button>Change state</button>
For stopping all the animations of the website, you need to manually stop each animation.
For stopping a jQuery animation, you can use .stop() helper. An example:
let paused = false; // state of the animation
let dir = 'down'; // to store the direction of animation so that the next time continues in the correct direction
let timeDown = 2000; // to animate properly after resuming
let timeUp = 2000; // to animate properly after resuming
// the initial calling of the animation
(function() {
slideDown();
})();
// function which resumes the animation
function animate() {
switch (dir) {
case 'up':
slideUp();
break;
case 'down':
slideDown();
break;
}
}
// a function to animate in the uppward direction
function slideUp() {
dir = 'up'; // setting direction to up
timeDown = 2000; // resetting the duration for slideDown function
$('div').stop().animate({
left: 0
}, {
duration: timeUp,
complete: slideDown, // calling slideDown function on complete
progress: function (animation, progress, ms) {
timeUp = ms; // changing the duration so that it looks smooth when the animation is resumed
}
}); // actual animation
}
// a function to animate in the downward direction
function slideDown() {
dir = 'down'; // setting direction to down
timeUp = 2000; // resetting the duration for slideDown function
$('div').stop().animate({
left: 200
}, {
duration: timeDown,
complete: slideUp, // calling slideUp function on complete
progress: function (animation, progress, ms) {
timeDown = ms; // changing the duration so that it looks smooth when the animation is resumed
}
}); // actual animation
}
// button click event listener
$('button').click(function() {
if (paused)
animate(); // to resume the animation
else
$('div').stop(); // to stop all the animations on the object
paused = !paused; // toggling state
});
div {
position: relative;
width: 100px;
height: 100px;
background: dodgerblue;
}
<button>Pause</button>
<div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For bootstrap, I don't think you have any bootstrap animations which needed to be paused in this scenario which you have mentioned since bootstrap animations depend on user interactions. If you want to prevent user interaction, you can put an overlay over the website says "Paused". Or, if you don't want to do that you can use CSS property pointer-events: none to disable all the pointer events.
Now for CSS animations, you can set a property called animation-play-state to paused.
If you want to change the state of the animations to paused when the user is not on the page (As I understood for your updated questions) you can use the new visibilityState API for that. There is an event visibilitychange which is fired when there a change in visibility.
document.addEventListener("visibilitychange", function() {
console.log( document.visibilityState );
document.querySelector('div').innerHTML = document.visibilityState;
});
<div>
Try opening a different tab or change the focus to another app
</div>
I have the following function :
function loadInfoBubble(aString)
{
$('#infoBubble').html('<h3>info :</h3><p>'+aString+'</p>');
infoBubble.style.display = "block";
var opacity = 9;
var vanishBlock = null;
var theTimeOut = setTimeout(function()
{
vanishBlock = setInterval(function()
{
if(opacity > 0)
{
opacity--;
}
infoBubble.style.opacity = "0."+opacity;
}, 100);
}, 7000);
var theTimeOut2 = setTimeout(function()
{
infoBubble.style.display = "none";
clearInterval(vanishBlock);
}, 9000);
}
This function is linked to a button by an onclick event.
The function is supposed to display a block which contains a sentence for 9 seconds, and after 7 seconds it starts to vanish.
It behaves normally for the first call, but if I click several times, it doesn't work anymore, even if I let the timeOuts end.
I don't understand why because each timeout or interval belongs to its own variable.
Your code never resets the opacity back to 1. Also, if you trigger the action again before a cycle is finished, the previous cycle isn't canceled. Thus if you trigger the bubble, and then trigger it again 5 seconds later, the first cycle will still run and the bubble will disappear in only 2 seconds. If you click again, the bubble will be faded by the cycle that started on the second click.
I think what you need to do is save the timer references with the bubble object itself, and then reset everything when you want to start a display cycle. You can use the jQuery .data() method for that:
function loadInfoBubble(aString) {
var $bubble = $("#infoBubble");
$bubble
.html('<h3>info :</h3><p>' + aString + '</p>')
.css({ display: "block", opacity: 1 });
var opacity = 9;
var timers = $bubble.data("timers") || {};
clearInterval(timers.vanishBlock);
clearTimeout(timers.showTimer);
clearTimeout(timers.clearTimer);
timers = {
showTimer: setTimeout(function() {
timers.vanishBlock = setInterval(function() {
if (opacity > 0) {
opacity--;
}
$bubble.css({ opacity: "0." + opacity });
}, 100);
}, 7000),
clearTimer: setTimeout(function() {
$bubble.css({ display: "none" });
clearInterval(timers.vanishBlock);
}, 9000)
};
$bubble.data("timers", timers);
}
jsfiddle
I'm totally a beginner with JavaScript and I'm trying to make a Javascript Countdown that loads an
I'm using this code for the countdown
<script language="Javascript">
var countdown;
var countdown_number;
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
if(countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
if(countdown_number > 0) {
countdown = setTimeout('countdown_trigger()', 1000);
}
}
}
function countdown_clear() {
clearTimeout(countdown);
}
</script>
I want to load exactly this after the count reaches 0... I am totally lost... what should I do?
It is basically a countdown that stops a music player after reaching 0. I would like to set up several countdowns with 10 mins, 15 mins, and 30 mins.
var countdown;
var countdown_number;
function countdown_init(time) {
countdown_number = time;
countdown_trigger();
}
function countdown_trigger() {
if (countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
setTimeout('countdown_trigger()', 1000)
} else { // when reach 0sec
stop_music()
}
}
function stop_music(){
window.location.href = "bgplayer-stop://"; //will redirect you automatically
}
Here is a simple example using mostly what you had above. This will need to be expanded a bit in order to have multiple countdowns but the general idea is here.
Fiddle: http://jsfiddle.net/zp6nfc9b/5/
HTML:
<a id="link_to_click" href="bgplayer-stop://">link</a>
<span id="countdown_text"></span>
JS:
var countdown_number;
var countdown_text = document.getElementById('countdown_text');
var link_to_click = document.getElementById('link_to_click');
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
countdown_number--;
countdown_text.innerHTML = countdown_number;
if (countdown_number > 0) {
setTimeout(
function () {
countdown_trigger();
}, 1000
);
}
else {
link_to_click.click();
}
}
link_to_click.addEventListener('click',
function () {
countdown_text.innerHTML = 'link was clicked after countdown';
}
);
countdown_init();
To explain some portions a little I think overall you had the correct idea.
I only added the eventListener so you could see the link was actually being clicked and displays a message in the countdown_text for you.
You didn't need to check countdown_number more than once so I removed that if block.
Also you don't really need to clear the timeout either. It clears itself once it executes. You only really need to clear a timeout if you want to stop it before it completes but since we rely on the timeout completing in order to do the next step its not necessary.
I need to call spinner on click and it need to show up 2 seconds and then disappear.I cant use setTimeout and setInterval...is there any other function for that?
Ok, here's a quick example using setTimeout.
HTML
<button>Click me</button><br>
<div id="spinner">I am a spinner</div>
CSS
#spinner {
display: none;
}
JavaScript
// pick up the elements to be used
var button = document.querySelector('button');
var spinner = document.querySelector('#spinner');
// add an event to the button so that `showThing` is run
// when it is clicked
button.onclick = showThing;
// `showThing` simply displays the spinner and then
// calls `removeThing` after 2 seconds
function showThing() {
spinner.style.display = 'block';
setTimeout(removeThing, 2000)
}
// and `removeThing` removes the spinner
function removeThing() {
spinner.style.display = 'none';
}
DEMO
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
RE: Your comment about setTimeout()
To use setTimeout just once...
setTimeout(myfunction(), 2000);
You could try setting up CSS animation to do this. An explanation of CSS animation can be found here:
https://css-tricks.com/almanac/properties/a/animation/
Or use a setTimeout like this:
Javascript:
$('#something').hide();
$('#clicky').on('click', function () {
$('#something').show();
setTimeout(function () {
$('#something').hide();
}, 2000);
});
HTML:
<button id="clicky">Click me</button>
<p id="something">Boo!</p>
http://jsfiddle.net/jonnyknowsbest/kkqqjz0v/