CSS Clip-Path Animation with Javascript - javascript

I try to animate the Clip-Path Property with JavaScript.
Means: It "grows" with help of SetTimeout.
I tried this, but it doesn't work.
http://jsfiddle.net/071dm2h3/8/
var el = document.getElementById("image")
function grow(i) {
el.style.clipPath = "circle("+ i +"px at 190px 160px)";
}
var i;
for(i = 0; i < 100; i++) {
setTimeout(grow(i), 400);
}
What am I missing here? Shouldn't the setTimeout change the value of I in every loop, so that I can see the result immediately?

To get this to work, I rewrote your setTimeout to be around your loop to make the image grow.
setTimeout( function(){
for(i = 0; i < 100; i++) {
grow(i)
}
},400);
Here is the jsfiddle

No, setTimeout fires once, and only once. Additionally, the way you are using setTimeout will lead to unintended results. You are basically saying:
I want to call grow(i) 400 milliseconds from now 100 times.
That means that 400 milliseconds from now, grow(i) will be called 100 times simultaneously. You don't want that, you want to call `grow(i) 100 times, waiting 400 milliseconds between each iteration.
Instead, you should either use setInterval which will wait a duration between each call or have each setTimeout schedule the next timeout after a duration.
Consider:
This will wait 2 seconds and then print 1,2,3,4 all at the same time.
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 2000);
}
This will print each iteration after a duration:
function iteration(i) {
console.log(i);
if (i > 3) return;
setTimeout(() => iteration(i + 1), 500);
}
iteration(0);

change you javascript to this
var el = document.getElementById("image")
function grow(i) {
console.log(i)
el.style.clipPath = "circle("+ i +"px at 190px 160px)";
}
var i;
for(i = 0; i < 100; i++) {
setTimeout( ((i) => () => grow(i))(i), i*10);
}
and kindly read this once
setTimeout in for-loop does not print consecutive values

Related

Can not set timeout in Node.js loop [duplicate]

This question already has answers here:
setTimeout in Node.js loop
(8 answers)
Closed 5 years ago.
Here, i tried to set timeout for every iteration but i could not make it because nature of nodejs. Is there any way to do that?
Thanks in advance
for (var i = 1; i <= 1000; i++) {
setTimeout(function () { console.log('something') }, 3000);
}
It works but it schedules all timeouts at the same time.
If you want to schedule them at 3 sec intervals then use:
for (var i = 1; i <= 1000; i++) {
setTimeout(function () { console.log('something') }, i * 3000);
}
If you want to use i inside of your timeout callbacks, use let instead of var like this:
for (let i = 1; i <= 1000; i++) {
setTimeout(function () { console.log('something', i) }, i * 3000);
}
As you can see with var it would print 1001 for every line:
for (var i = 1; i <= 1000; i++) {
setTimeout(function () { console.log('something', i) }, i * 3000);
}
And by the way, you can simplify it with arrow function syntax:
for (let i = 1; i <= 1000; i++) {
setTimeout(() => console.log('something', i), i * 3000);
}
Another way to do it would be to do something like this - instead of scheduling all 1000 timeouts at the same time, create an interval:
(() => {
let i = 0;
setInterval(() => {
i++;
console.log('something', i);
}, 3000);
})();
The outer closure is to keep the i variable from being visible in the outer scope. OR you can use something like this:
(() => {
let i = 0;
let f = () => {
i++;
console.log('something', i);
setTimeout(f, 3000);
};
setTimeout(f, 3000);
})();
In the last example the function that is invoked as a timeout callback schedules itself every time it finishes.
There are many ways to do it and all have some pros and cons.
For example you shouldn't use setInterval if your callback could potentially run longer than the interval between invocations. It will not be a problem when you use setTimeout and schedule yourself in every callback but on the other hand you may have less precision in the intervals that way. You need to test what works best for you.
for (var i = 1; i <= 10; i++) {
wait('something', i, 10);
}
function wait(msg, i, length){
setTimeout(function ()
{
console.log(msg) ;
}, (i * 3000));
}
try something like this.
Your code actually works but you wait 3 seconds for all which will wait about 1 ms before the next iteration is done runs
I think what you're really looking for is setInterval.
let runMeEveryThreeSeconds = function() {
console.log('hello!')
}
let threeSecondTimer = setInterval(runMeEveryThreeSeconds, 3000)
The timer will run forever, and every three seconds the word 'hello!' will be printed to your console. When you are ready to cancel the timer, you will need to:
clearInterval(threeSecondTimer)

How to set a delay inside a for loop

So I have a for loop and there is one line of code in there that opens a URL for each other iterations. I would like that line that opens the URL to wait 2 seconds before opening each one. How would I do it?
I tried the setTimeout function, but it iterates through the whole loop instantly after waiting the specified seconds, but I want it to wait for each iteration, not just before the iteration or during the first one.
The structure of my code looks something like this:
function someFunction(){
// do something
for(i = 0; i < range; i++){
//do something
//**open URL**
//do something
}
}
How would I make it wait 2 seconds for every iteration before executing that one specific line where it opens the URL? None of the other questions seem to help me, so I was wondering if anyone could help.
You can use settimeout
function delayedFunction(counter){
counter--;
console.log(counter);
if(counter){
setTimeout(function(){delayedFunction(counter); }, 1000);
}
}
delayedFunction(5);
You cannot do this in a for loop. You can do this with setInterval(). The setInterval() method will continue until clearInterval() is called.
Structure
var interval = setInterval(function() {
var i = 0;
if(i < x) {
...
} else {
clearInterval(interval);
}
}, ms);
Example
var urls = ["url1", "url2", "url3", "url4"];
function showDelayed(arr, ms) {
var i = 0;
var interval = setInterval(function() {
if (i < arr.length) {
// Do something here
console.log(arr[i]);
} else {
clearInterval(interval); // Clear when i === arr.length
}
i += 1; // Interval increments 1
}, ms);
}
showDelayed(urls, 300);
Not that this is a very good practice (opening up multiple URLS on an interval),
but since you asked.
var urlarray = ["https://www.mysite1.com", "https://www.mysite2.com", "https://www.mysite3.com"];
var currentURL = 0;
setInterval(function() {
if (currentURL < urlarray.length) {
alert(urlarray[currentURL]);
}
currentURL++;
}, 1500);

Repeating a function with a 1 second interval a certain number of times

So, I'm working on a timer and this is my code right now:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
function timerCreate() {
for (i = 0; i < 10; i++) {
sleep(1000);
minusOneSec();
}
}
All I wanted to do was that ten times, every one second, the minusOneSec() function was executed. (I took the code for the sleep() function from an answer I saw in StackOverflow some time ago and I don't remember who came up with it so if you know please tell me so I can credit them.) It works, but now it has come to my atention that this sleep function will stop all java script in the page while it's running. Is this true? What I also tried was this:
function timerCreate() {
for (i = 0; i < 10; i++) {
setInterval(minusOneSec, 1000);
}
}
but what it did was to run the minusOneSec() function 10 times in a row, then wait one second, then the function 10 times in a row, and so on. Is there a way to do what I intended but allowing other javascript code to run at the same time? I can use jQuery if necessary.
You need to call setInterval() just once (instead of in a loop) and check the counter inside. setInterval() will keep executing the passed function, till we clear the interval.
var i = 0,
interval = setInterval(function() {
minusOneSec();
i++;
if(i >= 10) clearInterval(interval); // stop it
}, 1000);

Delay javascript code execution inside for loop

I have the following for loop:
for (var i = tileLog.length - 1; i >= 0; i--) {
$('.' + tileLog[i]).mouseenter();
};
1 < tileLog.legth < 1025
Is there a way to delay each iteration of the loop so that mouseenter() is triggered every x miliseconds?
I have tried:
function doSetTimeout(i) {
setTimeout(function() { $('.' + i).mouseenter(); }, 250);
}
for (var i = tileLog.length - 1; i >= 0; i--)
doSetTimeout(tileLog[i]);
This doesn't seem to work, it just delays by 250ms then iterates through the loop
As an alternative to using setTimeout() you could also use setInterval().
Define a running variable in the outer scope (like your running i in the loop).
In each iteration, besides calling your function, decrement the running variable. If it is below zero, stop the setInterval()`` :
var index = tileLog.length - 1,
timer = setInterval( function(){
$('.' + tileLog[index]).mouseenter();
index -= 1;
if ( index < 0 ) {
clearInterval( timer );
}
}, 250 );
There is no actual sleep() function or something similar. Would also be problematic as JavaScript (for most cases) is single threaded and such a method would block the render thread, thus rendering your browser inaccessible.
There is no sleep or such in JavaScript. So your approach with timeout is correct.
var tileLog;
var i = titleLog.length - 1;
function func1() {
$('.' + tileLog[i]).mouseenter();
if (--i) {
window.setTimeout(func1, 250);
}
}
// and of course start the process
func1();

How to create pause or delay in FOR loop?

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or jQuery
This is a test example
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
s.innerHTML = s.innerHTML + i.toString();
//create a pause of 2 seconds.
}
You can't use a delay in the function, because then the change that you do to the element would not show up until you exit the function.
Use the setTimeout to run pieces of code at a later time:
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
// create a closure to preserve the value of "i"
(function(i){
window.setTimeout(function(){
s.innerHTML = s.innerHTML + i.toString();
}, i * 2000);
}(i));
}
var wonderfulFunction = function(i) {
var s = document.getElementById("div1"); //you could pass this element as a parameter as well
i = i || 0;
if(i < 10) {
s.innerHTML = s.innerHTML + i.toString();
i++;
//create a pause of 2 seconds.
setTimeout(function() { wonderfulFunction(i) }, 2000);
}
}
//first call
wonderfulFunction(); //or wonderfulFunction(0);
You can't pause javascript code, the whole language is made to work with events, the solution I provided let's you execute the function with some delay, but the execution never stops.
I tried all one, but I think this code is better one, it is very simple code.
var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString(); i++;}, 2000);
if you want to create pause or delay in FOR loop,the only real method is
while (true) {
if( new Date()-startTime >= 2000) {
break;
}
}
the startTime is the time before you run the while
but this method will cause the browsers become very slow
It is impossible to directly pause a Javascript function within a for loop then later resume at that point.
This is how you should do it
var i = 0;
setTimeout(function() {
s.innerHTML = s.innerHTML + i.toString();
i++;
},2000);
The following code is an example of pseudo-multithreading that you can do in JS, it's roughly an example of how you can delay each iteration of a loop:
var counter = 0;
// A single iteration of your loop
// log the current value of counter as an example
// then wait before doing the next iteration
function printCounter() {
console.log(counter);
counter++;
if (counter < 10)
setTimeout(printCounter, 1000);
}
// Start the loop
printCounter();
While several of the other answers would work, I find the code to be less elegant. The Frame.js library was designed to solve this problem exactly. Using Frame you could do it like this:
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
Frame(2000, function(callback){ // each iteration would pause by 2 secs
s.innerHTML = s.innerHTML + i.toString();
callback();
});
}
Frame.start();
In this case, it is nearly the same as the examples that use setTimeout, but Frame offers a lot of advantages, especially if the you are trying to do multiple or nested timeouts, or have a larger JS application that the timeouts need to work within.
I am executing a function where I need access to the outside object properties. So, the closure in Guffa solution doesn't work for me. I found a variation of nicosantangelo solution by simply wrapping the setTimeout in an if statement so it doesn't run forever.
var i = 0;
function test(){
rootObj.arrayOfObj[i].someFunction();
i++;
if( i < rootObj.arrayOfObj.length ){
setTimeout(test, 50 ); //50ms delay
}
}
test();
The way I found was to simply use setInterval() to loop instead. Here's my code example :
var i = 0;
var inte = setInterval(() => {
doSomething();
if (i == 9) clearInterval(inte);
i++;
}, 1000);
function doSomething() {
console.log(i);
};
This loops from 0 to 9 waiting 1 second in between each iteration.
Output :
0 1 2 3 4 5 6 7 8 9
It is not possible to pause a loop. However you can delay the execution of code fragments with the setTimeout() function. It would not make a lot of sense to pause the entire execution anyway.
I am using while loop and check the pause variable to check the user pause/resume the code.
var pause = false;
(async () => {
for (let index = 0; index < 1000; index++) {
while (pause) {
await new Promise((res) => setTimeout(res, 1000));
console.log("waiting");
}
await new Promise((res) => setTimeout(res, 1000));
console.log(index);
}
})();
const pausefunc = async () => {
pause = true;
};
const playfunc = () => {
pause = false;
};
<button onclick="playfunc()">Play</button>
<button onclick="pausefunc()">Pause</button>
I used a do...while loop to put a delay in my code for a modal dialog that was closing too quickly.
your stuff....
var tNow = Date.now();
var dateDiff = 0;
do {
dateDiff = Date.now() - tNow;
} while (dateDiff < 1000); //milliseconds - 2000 = 2 seconds
your stuff....

Categories

Resources