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/
Related
let timer = document.querySelector("#timer");
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
btn.onclick = function() {
text.innerHTML += 'clicked' + '<br>'
}
var myTimer = setInterval(myFn, 1000);
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
I'm trying with this small code to read the div#timer every second and check for a click condition in console.log() F12. It gives me different error in every way I try to do it.
let timer = document.querySelector("#timer");
let btn = document.querySelector("#btn");
setInterval(() => {
console.log(timer.textContent)
if (timer.textContent === '0') {
btn.click()
}
}, 1000);
Consider the following jQuery example.
$(function() {
var timer = 0;
var counter = 3;
var timeObj = $("#timer");
var btnObj = $("#btn");
var txtObj = $("#text");
var interval;
function myFn() {
if (--counter >= 0) {
txtObj.append("Clicked<br />");
} else {
clearInterval(interval);
}
}
interval = setInterval(function() {
timeObj.html(++timer);
}, 1000);
btnObj.click(myFn);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">0</div>
<button id="btn">Button</button>
<div id="text"></div>
You will want to use setInterval() and not setTimeout().
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
See more: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Using the -- and ++ before the variable will also apply the change before it is used.
The decrement operator (--) decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Adjusting the logic here can also ensure that the button click does allow the user to keep performing actions.
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>
In my application, I add a loaderDiv to avoid all userevents on the page.
The loader appears. If the user force a clickevent(eg. greenContainer onclick) the event is fired after the loader div disappears.
I've created a short example the show you the problem
js:
function appendOverlay(){
var maskDiv = $('<div id="overlay" class="loadmask" onclick:"return false;"><div class="removeDiv" onclick="sleep(3000)"><span>click to remove overlay after 3 seconds</span></div></div>');
$('body').append(maskDiv);
}
function removeDiv(){
$("#overlay").remove();
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
removeDiv();
}
Demo
How can I solve this problem?
Solved this problem by using setTimeout(removeDiv(),0).
This is a problem with the event loop execution in Javascript.
Propergate the removeDiv() to the next tick and the userEvent onClick() is execute first.
Why is setTimeout(fn, 0) sometimes useful?
The JavaScript Event Loop
Strange 'sleep' function there.
Why don't u use the internal timeout :
function sleep(milliseconds) {
setTimeout(function() {
removeDiv();
}, milliseconds);
}
DEMO
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);
}
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>