How to add a setTimeout() to a query selector - javascript

I have a JS script
<script>
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
this.style.backgroundColor = 'black';
})
});
</script>
I want to wait 10 seconds before running. I have tried
<script>
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', setTimeout(function() {
this.style.backgroundColor = 'black';
}),10000)
});
</script>
But I get a console error of can not define this

setTimeout should be invoked inside the callback.
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
setTimeout(()=>this.style.backgroundColor = 'black', 10000);
})
});

Related

show one line per second in javascript

I want to show one line per second in javascript, but it is not working...
https://jsfiddle.net/d9a784ta/
function showIt1() {
document.getElementById("div1").style.visibility = "visible";
}
function showIt2() {
document.getElementById("div2").style.visibility = "visible";
}
function showIt3() {
document.getElementById("div3").style.visibility = "visible";
}
window.onload = function() {
setTimeout("showIt1()", 1000);
setTimeout("showIt2()", 2000);
setTimeout("showIt3()", 3000);
}
You could use display property with block value, because it overwrites the initial display: none.
For using setTimeout, you could insert the reference to the function, without using strings and supply the parameter for the id and use only one function.
function showIt(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function() {
setTimeout(showIt, 1000, 'div1');
setTimeout(showIt, 2000, 'div2');
setTimeout(showIt, 3000, 'div3');
};
#div1, #div2, #div3 { display: none; }
<div id="div1"><h1>1 line</h1></div>
<div id="div2"><h1>2 line</h1></div>
<div id="div3"><h1>3 line</h1></div>
You need to reference the function directly, not with a string:
function showIt1() {
document.getElementById("div1").style.visibility = "visible";
}
function showIt2() {
document.getElementById("div2").style.visibility = "visible";
}
function showIt3() {
document.getElementById("div3").style.visibility = "visible";
}
window.onload = function() {
setTimeout(showIt1, 1000);
setTimeout(showIt2, 2000);
setTimeout(showIt3, 3000);
}
In setTimeout, you provide first argument as string. It should be a name of function, like this:
setTimeout(showIt1, 1000);
So, it all would look like:
function showIt1() {
document.getElementById("div1").style.visibility = "visible";
}
function showIt2() {
document.getElementById("div2").style.visibility = "visible";
}
function showIt3() {
document.getElementById("div3").style.visibility = "visible";
}
window.onload = function() {
setTimeout(showIt1, 1000);
setTimeout(showIt2, 2000);
setTimeout(showIt3, 3000);
}
setTimeout() accepts Function as it's first parameter. When you create a function called showIt1, then when you for example write to the console something like this:
console.log(showIt1)
It will output: "Function". So that's why you are also allowed to call setTimeout() like this:
setTimeout(function() {
document.getElementById("div1").style.visibility = "visible";
}, 1000);
A few things:
1) changed document.getElementById for JQquery $("#id")
2) added quotes on your <div> ids
3) using .css() function:
HTML:
<div id="div1"><h1>1 line</h1></div>
<div id="div2"><h1>2 line</h1></div>
<div id="div3"><h1>3 line</h1></div>
JS:
function showIt1() {
$("#div1").css('display','block');
}
function showIt2() {
$("#div2").css('display','block');
}
function showIt3() {
$("#div3").css('display','block');
}
window.onload = function() {
console.log('onload');
setTimeout("showIt1()", 1000);
setTimeout("showIt2()", 2000);
setTimeout("showIt3()", 3000);
}
JSFiddle:https://jsfiddle.net/dudu84/d9a784ta/2/

Dynamically added function still running even after remove from DOM

This script has been added dynamically. It has a timeout function, means that it runs every 5 seconds.
dynamicjs.php
$(document).ready(function(){
(function( $ ){
$.fn.baslatmesajlari = function() {
setInterval(function(){
console.log("I am running");
}, 5000);
return this;
};
})( jQuery );
});
$("body").baslatmesajlari();
I load this function to a div using;
$("#temporarycontent").load("dynamicjs.php");
And when I do
$("#temporarycontent").empty();
The script is still running. How can I stop it run ?
You can't, you need a handle to the intervalId returned by the setInterval function or provide an API on the plugin in order to destroy it and cleanup after itself. The easiest way would be to attach the state of the plugin to the DOM element on which it was applied.
(function ($) {
const PLUGIN_NAME = 'baslatmesajlari';
function Plugin($el) {
this.$el = $el;
this._timerId = setInterval(function () {
console.log('running');
}, 2000);
}
Plugin.prototype.destroy = function () {
this.$el.removeData(PLUGIN_NAME);
clearInterval(this._timerId);
};
$.fn[PLUGIN_NAME] = function () {
if (!this.data(PLUGIN_NAME)) this.data(PLUGIN_NAME, new Plugin(this));
return this;
};
})(jQuery);
$(function () {
var plugin = $('#plugin').baslatmesajlari().data('baslatmesajlari');
$('#destroy').click(function () {
plugin.destroy();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="plugin"></div>
<button id="destroy">Destroy plugin</button>
You must have a reference to the interval id, then, when you want to stop it's execution, call clearInterval(the_id)
let interval = null //this is the variable which will hold the setInterval id
$(document).ready(function () {
(function ($) {
$.fn.baslatmesajlari = function() {
interval = setInterval(function () {
console.log('I am running')
}, 5000)
return this
}
})(jQuery)
})
$("body").baslatmesajlari()
And then:
$("#temporarycontent").empty();
clearInterval(interval) // it should stop the function.
Hope it helps.

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!

adding a timeout delay to 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);
};

Can a body tag hold multiply onload="setInterval()"?

Can a body tag hold two set intervals? or have 2 functions use the same interval?
ex:
<body onload="setInterval(function1, 500); setInterval(function2, 1000);">
<body onload="setInterval(function1, function2, 500");>
You can create a function that calls setInterval() twice with the different functions and call it on the body.onload().
And i dont think that 2 functions can have the same interval unless you wrap them up in one or call them inline like this:
<body onload="setInterval(function(){ function1(); function2();}, 500);">
Your first example would be fine:
window.onload = function() {
setInterval(function1, 500);
setInterval(function2, 1000);
}
function function1() {
console.log("function1");
}
function function2() {
console.log("function2");
}
See an example of the above code working here.
Simply use jQuery and register an event handler (in a <script type="text/javascript"> block).
In case all you need is the DOM tree being available:
$(document).ready(function() {
setInterval(function1, 500);
setInterval(function2, 1000);
});
otherwise (if you need all images being loaded etc):
$(window).load(function() {
setInterval(function1, 500);
setInterval(function2, 1000);
});
Instantiate as many onloads as you need without the collisions.
<SCRIPT>
// Class Definition
OnLoad = function(taskFunction,miliseconds) {
var context = this;
context.cnt = 0;
context.id = null;
context.doTask=taskFunction;
context.interval = function() {
if(document.readyState == "complete"){
try{ context.stop();} catch(e){ throw new Error("stop error: " + context.id); }
try{ context.doTask();} catch(e){ throw new Error("load error: " + context.id); }
}
};
context.start = function(timing) {
if(context.id && context.id!=null)
context.stop();
context.cnt=0;
context.id=setInterval(context.interval,timing);
};
context.stop = function() {
var _id = context.id;
clearInterval(context.id);
context.id=null;
};
context.start(miliseconds ? miliseconds : 100);
};
// Example Onloads
new OnLoad(function(){
alert("onload 1");
}); // uses default timing of 100 miliseconds
new OnLoad(function(){
alert("onload 2");
},200);
new OnLoad(function(){
alert("onload 3");
},300);
</SCRIPT>
Try This Cod it's Easy.
you can run this here and TEST it.
window.onload = function() {
function foo() {
Load_Note();
}
setInterval(foo, 3600);}
function Load_Note() {console.log("api loded")}

Categories

Resources