I have some loop like below..which clicks all buttons
for(var i = 1;i<document.querySelectorAll(".myclass").length;i++){
document.querySelectorAll(".myclass")[i].click();
console.log("hi");
};
but I want to add sleep function that delays each loop like sleep(2000); , Is there any function in javascript like that ?
I tried below code , but does not work
for(var i = 1;i<document.querySelectorAll(".myclass").length;i++){
setTimeout(function() {
document.querySelectorAll(".myclass")[i].click();
console.log("hi");
}, (3 * 1000));
};
var myVar = setInterval(myTimer, 2000);
var divIndex = 0;
function myTimer() {
if(divIndex < document.querySelectorAll(".myclass").length){
document.querySelectorAll(".myclass")[divIndex].click();
console.log(divIndex);
}else {
clearInterval(myVar);
}
divIndex++;
}
<div class='myclass'></div>
<div class='myclass'></div>
<div class='myclass'></div>
<div class='myclass'></div>
Create the new function as give and call that function inside your loop.
function sleep(milliseconds) {
var start = new Date().getTime();
while ((new Date().getTime() - start) < milliseconds) {
}
}
for (i = 0; i < 3; i++) {
console.log(i);
sleep(5000);
}
Related
Hi! I'm trying to create a carousel/image slider which is automatic and reactable to onclick event but for somereason the onclick event messesup the automatic flow of the slider even though the code makes perfect sens!
Could someone tell me whats wrong in this code and a solution to fix it please! thank you!
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
prevbutton.addEventListener("click",leftbuttonclick);
function rightbuttonclick(){
i++;
changeImg();
}
function leftbuttonclick(){
i--;
changeImg();
}
function changeImg(){
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
function changenext(){
i++;
changeImg();
}
// Run function when page loads
window.onload=changeImg;
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200"/>
<button id="rightbutton">right</button>
here is a code that can help you,
var prevbutton=document.querySelector("#leftbutton");
//nextbutton.addEventListener("click",leftbuttonclick);
prevbutton.addEventListener("click",leftbuttonclick);
Keep a variable eg: setTime that decides whether to call setTimeout again or not.
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload = changeImg();
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
Or you can use setInterval instead of setTimeout as shown below:
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
}
window.onload = changeImg();
setInterval(function() {
changeImg()
}, time);
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
add a clearTimeout function to chageImg() and it will work,
as to why it was behaving strangely is because setTimeout was been called multiple times. you should always be careful when using setInverval or setTimeout. here is a code snippet
function changeImg(){
clearTimeout(interval);
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
interval = setTimeout("changeImg()", time);
}
Javascript
function myFunction() {
for (i = 0; i < 5000;) {
setTimeout(function() {
document.getElementById("demo").innerHTML = i;
}, i);
i += 500;
}
}
HTML
<body onload="myFunction()">
<div id="demo"></div>
How to increase " i " every 5ms and print it in #demo every time it changes
I am trying to make a look that increases the value of ( i ) once every 5ms, and prints it out in # demo.
Right now, the value 5000 immediately prints out as soon as I run the script for some reason, as opposed to increasing by 500 every time.
Thanks in advance.
You can change myFunction to:
var i = 0;
function myFunction() {
var timerId = setInterval(function(){
if(i >= 5000)
{
clearInterval(timerId);
}
document.getElementById("demo").innerHTML = i;
i +=500;
}, 5);
}
this should work.
var i=0;
function looper(){
setTimeout(function(){
console.log(i+" data");
i=i+500;
if(i<5000)
looper();
}, i);
}
looper();
function myFunction() {
var i = 0;
var max = 5000;
var step = 500;
var intervalMs = 5;
var interval = setInterval(function() {
// clear interval if one step before max value
if (i >= max-step) {
clearInterval(interval);
}
// increment i by step
i+=step;
// set inner html of div
document.getElementById("demo").innerHTML = i;
}, intervalMs)
}
Plunkr: https://plnkr.co/edit/IfkGOpjUnf4sKpN4iCZ4?p=preview
If you want your code to look similar to what you have, you can use an IIFE:
function myFunction() {
for (i = 0; i <= 5000;i += 500) {
(function(index) {
setTimeout(function() {
document.getElementById("demo").innerHTML = index;
}, index);
})(i);
}
}
<body onload="myFunction()">
<div id="demo"></div>
</body>
You are having an issue with the closure not saving a reference to your timeout. Subsequent arguments after the second are passed into the callback function as arguments.
Here we are passing i as the third argument
setTimeout(fn, delay, i)
Then in the callaback we have access to the i, we are reassigning it to x within the scope of the callback.
function myFunction() {
for (i = 0; i <= 5000; i = i + 500) {
setTimeout(function(x) {
document.getElementById("demo").innerHTML = x;
}, i, i);
}
}
myFunction()
<div id="demo"></div>
function myFunction(max, ii = 0) {
document.getElementById('demo').innerHTML = ii
if (ii < max) {
setTimeout(myFunction, 500, max, ii + 500)
}
}
myFunction(5000)
<div id="demo"></div>
**
<div id="demo"></div>
<script>
function myFunction() {
var i = 0;
var setClock = function() {
if (i < 5000) {
local = i;
i += 500;
setTimeout(function() {document.getElementById("demo").innerHTML = local; setTimeout(setClock, 500);},
500);
}
}
setClock();
}
**
you should wrap scripts in tags
the javascript Closures. You should know that because of the Closures, second parameters for all setTimeout() are 5000, which is the i's final value. You can avoid the Closure by the codes I showed or erase the impact of Closure by below codes:
<div id="demo"></div>
<script>
function myFunction() {
var local;
for (i = 0; i < 5000; i+= 500) {
local = i;
setTimeout((function(interval){
return function() {document.getElementById("demo").innerHTML = interval;} ;
})(local), (function(interval){return interval})(local));
}
}
How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>
I have the code segment:
var i = 0;
(function loop() {
text_objects[i].displayText();
if (++i < text_objects.length) {
setTimeout(loop, 3000);
}
})();
Which is supposed to display the contents of an array one at a time, separated by 3 seconds. However, when I run the program, I only get the first item, and it sort of just freezes there, without updating and showing the rest of the items in the array.
What am I doing wrong?
As correctly mentioned by #nnnnnn,
loop() is a named function expression, and the reference loop should be in scope within the function
Also your code works fine.
var i = 0;
var test = function(value){
this.text = value;
}
test.prototype.displayText = function(){
document.write(this.text + "<br/>");
}
var text_objects = [];
for (var j = 0; j<10; j++){ text_objects.push(new test(j)); }
(function loop() {
text_objects[i].displayText();
if (++i < text_objects.length) {
setTimeout(loop, 3000);
}
})();
Alternate approach:
var i = 0;
function loop() {
document.write(i + "<br/>")
if (++i < 5) {
setTimeout(loop, 3000);
}
}
loop();
This works fine. Not sure if this is what you expect?
var i = 0;
Array.prototype.displayText = function(i) {
console.log(this[i]);
};
var text_objects = ['1', '2', '3'];
(function loop() {
text_objects.displayText(i);
if (++i < text_objects.length) {
setTimeout(loop, 3000);
}
})();
Following is my approach to the answer. Hope I helped!
var i = 0;
function loop() {
text_objects[i].displayText();
i = i + 1;
if (i < text_objects.length) {
setTimeout(loop, 3000);
};
};
setTimout(loop, 3000);
I did 2 countdowns events but I can't stop the setTimeout (countDown) function later using the clearTimeout. This is my jQuery:
$(document).ready(function () {
var lives = 5
var livesmenos1 = "4";
var livesmenos1 = 4;
var countdownfinal = 10;
var t;
var isTimeron = false;
var onelive = "1";
var onelive = 1;
$(".wrongbutton, .wrongbutton2, .wrongbutton3").click(function () {
$(".countdownfirst").text(livesmenos1)
livesmenos1--;
if (livesmenos1 == 0) (livesmenos1 = 0);
if (livesmenos1 < 2)
$(".countdownfirst").css({ "color": "990099", "font-size": "380%" });
if (livesmenos1 < 1)
$(".lives").attr("src", "images/morelives.gif");
if (livesmenos1 < 0)
$("#tableone, #tabletwo").delay(1000).hide(2000);
if (livesmenos1 < 0)
$("#tableloser").delay(2000).fadeIn(2500, function countDown() {
setTimeout(countDown, 1000);
$("#box").text(countdownfinal + " seconds").css({ "color": "990099" });
countdownfinal--;
if (countdownfinal < 1) (countdownfinal = 10);
if (countdownfinal < 2)
$(".countdownfirst").text(onelive++);
if (onelive > 5)
$(".countdownfirst").text("5");
if (onelive > 1)
$("#nextbuttonloser").delay(1000).fadeIn(500).delay(30000);
});
});
});
then I did the myStopFunction onclick button to start the clearTimeOut function:
function myStopFunction()
{
clearTimeout(countDown);
}
and it doesn't work. I tried to trigger also using jQuery but again, with no effect. How can i do to stop the setTimeout function named "countDown"?
thanks
There is no way to stop a specific function from firing in a Timeout. The only way is to stop the timeout itself. Every timeout returns an integer value when it is called. Use this value to clear the timeout. Note that it is going to need to be available to the scope of your function
var TimeoutHandle;
$(document).ready(function () {
...
TimeoutHandle = setTimeout(countDown, 1000);
...
});
function myStopFunction()
{
clearTimeout(TimeoutHandle);
}