adding a timeout delay to javascript? - javascript

can someone help me please i am trying to make this javascript start its function after a 3 second delay using time out.
I am still learning javascript and jquery and would be grateful if someone could show me where im going wrong and how to fix it.
Thank you.
<script type="text/javascript">
setTimeout(function(){
window.onload = function showPopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100%"
}
}
},3000);
</script>

So in short, you have this:
setTimeout(function () {
window.onload = function() {
// do stuff...
}
}, 3000);
That's not going to work. This says, after 3 seconds, assign a handler for the window's onload event. At that point the event already (most likely) fired. So this funciton won't execute.
Instead, flip it around.
window.onload = function() {
setTimeout(function () {
// do stuff...
}, 3000);
}
So here, when the window loads, you do something 3 seconds later.

This is wrong:
setTimeout(function () {
window.onload = function showPopUp(el) {
This assigns an onload handler after 3 seconds, by which time the window has likely already loaded.
Get rid of the window.onload = function showPopUp(el) {...} part to wait 3 seconds from when the script loaded.
setTimeout(function () {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100%"
}
}, 3000);
Or reverse the setTimeout and window.onload to wait 3 seconds after all the resources finished loading.
window.onload = function showPopUp(el) {
setTimeout(function () {
// ...
}, 3000);
};

Related

How to force the redraw of an element inside a callback in javascript?

I would like to do something as simple as this:
Basically, I toggle the visibility of a loader element, then I simulate the processing of something by waiting 10 seconds and finally I toggle the visibility again. My problem is that I would like to force the redraw inside the testLoader callback function, but so far the update of the elements is only done after the callback has finished its execution. Is there a way of redrawing while the button callback is being executed?
testLoader : function() {
var loader = document.getElementById("loader")
var loaderVisibility = loader.style.visibility;
if (loaderVisibility == "visible") {
loader.style.visibility = "hidden"
} else {
loader.style.visibility = "visible"
}
var ms = 10000;
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
if (loaderVisibility == "visible") {
loader.style.visibility = "hidden"
} else {
loader.style.visibility = "visible"
}
}
<input type="button" id="testLoaderButton" value="Test Loader" onClick="testLoader()" />
Use setTimeout and don't block eventloop by using while
function testLoader() {
var loader = document.getElementById("testLoaderButton");
var loaderVisibility = loader.style.visibility;
loader.style.visibility = "hidden";
setTimeout(function () {
loader.style.visibility = "visible";
}, 1000);
}
<input type="button" id="testLoaderButton" value="Test Loader" onClick="testLoader()" />
In the end I came up with the following solution:
testLoader : function()
{
var loader = document.getElementById("loader");
loader.style.visibility = "visible";
setTimeout(function () {
do_processing()
loader.style.visibility = "hidden";
}, 500)
}
Basically I execute the code in another thread by using setTimeout and thus I dont block the javascript UI. PS: I know that Web Workers allow to simulate the creation of threads in javascript, but I preferred not to restructure my code into different files.

Button to start/stop an infinite loop through functions with delay between each

I'm trying to create a function that on the click of a button will start a loop through each function with a 5 second delay between each and loop infinitely until the button is clicked again. I'm close with this, but after 5 seconds, it only just executes the last function in the set (tuesday) and does not iterate through them with a delay between each.
function links() {
safety
daily
monday
tuesday
}
var intervalId;
function toggleIntervalb() {
if (!intervalId) {
intervalId = setTimeout(links, 5000);
} else {
clearInterval(intervalId);
intervalId = null;
}
}
function safety(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'block';
document.getElementById("daily").style.display = 'none';
document.getElementById("monday").style.display = 'none';
document.getElementById("tuesday").style.display = 'none';
}
function daily(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'none';
document.getElementById("daily").style.display = 'block';
document.getElementById("monday").style.display = 'none';
document.getElementById("tuesday").style.display = 'none';
}
function monday(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'none';
document.getElementById("daily").style.display = 'none';
document.getElementById("monday").style.display = 'block';
document.getElementById("tuesday").style.display = 'none';
function tuesday(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'none';
document.getElementById("daily").style.display = 'none';
document.getElementById("monday").style.display = 'none';
document.getElementById("tuesday").style.display = 'block';
**2nd Attempt:
Closer with this (includes button)
New to jsfiddle - can't make my code work here: https://jsfiddle.net/unqrhxtp/16
So, I am also including the pastebin (save as .html and open): https://pastebin.com/EwHVqmHJ
Currently, the code stops after executing the first function. It appears to loop on the first element only (if you click another link manually, it forces back to the first function in the set).
Thanks in advance.
Changing this line:
intervalId = setTimeout(links, 5000);
from a setTimeout to a setInterval will probably fix that
intervalId = setInterval(links, 5000);
Update
After reading your updated question I think something like this will solve your problem:
// Gather functions in an array, easier to loop trough
var links = [
safety,
daily,
monday,
tuesday,
wednesday,
thursday
]
function cyclelinks() {
links.forEach(function(link, index) {
var delay = index * 5000;
var fn = links[index];
setTimeout(fn, delay)
});
}
var intervalId;
function toggleInterval() {
var btn = document.getElementById("logo");
if (!intervalId) {
var delay = links.length * 5000; // repeat after all functions are called with 5 sec delay
cyclelinks()
intervalId = setInterval(cyclelinks, delay);
} else {
clearInterval(intervalId);
intervalId = null;
location.reload();
}
}
You should use setInterval because setTimeout runs after gived time means it works correctly because. If you run this code step by step then you can see what i am saying. When cursor on the settimeout your functions doesnt work immediately it will wait 5 secs.
I hope i could help
I managed to come up with a solution, although I'm not totally happy with it. Mostly because it forces me to wait a full 90 seconds before the looping starts. For now, this will do, but I'll leave this open in hopes someone will post a better solution.
//Loop through links upon click
function cyclelinks() {
setTimeout(safety, 10000);
setTimeout(daily, 20000);
setTimeout(monday, 30000);
setTimeout(tuesday, 40000);
setTimeout(wednesday, 50000);
setTimeout(thursday, 60000);
}
var intervalId;
function toggleInterval() {
var btn = document.getElementById("logo");
if (!intervalId) {
intervalId = setInterval(cyclelinks, 90000);
} else {
clearInterval(intervalId);
intervalId = null;
location.reload();
}
}

use onmousemove to reset setTimeout() to start over again(・・?

when mouse moves, the timer function cancelled =="
but i actually want it to count from the beginning instead.
function w()
{
if (parent.C.location == "http://119.247.250.128/wasyoku/home/prime.html")
{ parent.C.location = "weather.html";
wTout = setTimeout(function(){ parent.C.location = "prime.html"; }, wT);
}
else { parent.C.location = "prime.html"; clearTimeout(wTout); }
}
document.onmousemove.clearTimeout(wTout);
do i really need to setTimeout again(・・?
wTout = setTimeout(function(){ parent.C.location = "prime.html"; }, wT);
Yes, if you clear the timeout you have to set it again.
Another thing you can do is set a variable as the last time you moved the mouse and on the ontimeout you can set another settimeout if you moved the mouse in XX seconds
var sto = null;
function myTimeout() {
window.clearTimeout(sto);
sto = setTimeout(function() {
console.log("setTimeout's working");
}, 2000);
}
someElement.addEventListener('mousemove', function() {
myTimeout();
});
jsfiddle DEMO

Javascript blinking with setTimeouts

Helllo i am getting problem with blinking every 0.5 seconds. I start my code with #blink display= "inline" but it always stays inline. When starting my code, i call startBlinking.
function startBlinking() {
setInterval(function () {
blink();
}, 1000);
}
function blink() {
setTimeout(function () {
document.getElementById('blink').style.display = "none";
}, 500);
setTimeout(function () {
document.getElementById('blink').style.display = "inline";
}, 500);
}
Can you help me? Thanks.
The problem with your attemt is that you're setting the same timeout length for both hiding and showing the element, meaning it will hide and show again at the same time! Remove one and it should work:
function startBlinking() {
setInterval(function () {
blink();
}, 1000);
}
function blink() {
// note no timeout for the hiding part
document.getElementById('blink').style.display = "none";
setTimeout(function () {
document.getElementById('blink').style.display = "inline";
}, 500);
}
startBlinking();
<div id="blink">blink</div>
<p>some text following</p>
As you can tell, this causes the following content to jump. We are also fetching the element every time we're hiding or showing it. Better to swap to using visibility and make the function a bit more flexible:
function blink(element, time) {
// using visibility: hidden; instead of display: none;
// allows the element to keep its rendering space
element.style.visibility = "hidden";
setTimeout(function () {
element.style.visibility = "visible";
}, time);
setTimeout(function () {
blink(element, time); // recurse
}, time * 2);
}
// query the DOM for element once instead of every iteration
blink(document.getElementById("blink"), 500);
<div id="blink">blink</div>
<p>following content stays put</p>
You might also want to be able to stop the blinking at some point
function blink(element, time) {
function loop(){
element.style.visibility = "hidden";
setTimeout(function () {
element.style.visibility = "visible";
}, time);
timer = setTimeout(function () {
loop();
}, time * 2);
cleared = false;
}
var timer, cleared = true;
// expose methods
return {
start: function() {
if (cleared) loop();
},
stop: function() {
clearTimeout(timer);
cleared = true;
}
};
}
var blinking = blink(document.getElementById("blink"), 500);
document.getElementById("start").addEventListener("click", function(){
blinking.start();
});
document.getElementById("stop").addEventListener("click", function(){
blinking.stop();
});
<div id="blink">blink div</div>
<button id="start">start blinking</button><br />
<button id="stop">stop blinking</button>
you can make it simple by toggling a class
.hide{
display:none;
}
setInterval(function () {
$('.blink').toggleClass('hide')
}, 500);
JS Fiddle
Just call it once, setTimeout() is ripping it out of the thread so it gets set right back to inline.
function blink() {
setTimeout(function () {
if (document.getElementById('blink').style.display === 'inline') {
document.getElementById('blink').style.display = "none";
} else {
document.getElementById('blink').style.display = "inline";
}
}, 500);
}
you have messed up the event que of javascript, why dont you try this
function startBlinking() {
initial = 'inline';
index = 0;
setInterval(function () {
if(index==2){
initial = (initial=='none')?'block':'none';
document.getElementById('blink').style.display = initial;
index=0;
}
index++;
}, 1000);
}
For the jQuery fans:
you can use the 'pulsate' effect
http://jqueryui.com/effect/
This may or may not achieve the exact blinking you need but it's a lot simpler!

Clearing an interval that was set before [duplicate]

This question already has answers here:
How can I use setInterval and clearInterval?
(5 answers)
Closed 8 years ago.
http://jsfiddle.net/x5MY8/2/
HTML
<div id="easy">easy</div>
<div id="hard">hard</div>
JS
function test(mode) {
var asd = this;
this.mode = mode;
setInterval(function () {
alert(asd.mode);
}, 1000);
}
$(document).ready(function () {
$('#easy').on('click', function () {
var stuff = new test('easy');
});
$('#hard').on('click', function () {
var stuff = new test('hard');
});
});
Upon pressing the easy button, an event launches that alerts easy every second. If I press hard afterwards, it will start another event, and it will alert easy, hard, easy, hard.., but I want it to alert only what was pressed at the moment, so I have to clear the previous interval somehow. How can I do that? Somehow, I need to call clearInterval when a button is pressed on the other object, but I don't really know how to.
http://jsfiddle.net/x5MY8/3/
You need to store and clear the interval like so
var interval;
function test(mode) {
var asd = this;
this.mode = mode;
if (interval) {
clearInterval(interval);
}
interval = setInterval(function () {
alert(asd.mode);
}, 1000);
}
Store it in a variable:
var interval = setInterval(function(){
//your code
},1000);
Now, you can clear using clearInterval:
clearInterval(interval);
clear the value when every clicked
var clear=0;
function test(mode) {
var asd = this;
this.mode = mode;
clear=setInterval(function () {
alert(asd.mode);
}, 1000);
}
$(document).ready(function () {
$('#easy').on('click', function () {
clearInterval(clear);
var stuff = new test('easy');
});
$('#hard').on('click', function () {
clearInterval(clear);
var stuff = new test('hard');
});
});

Categories

Resources