0
Please can someone help me. I need to create a delay/sleep function in JS
I'll be using it in a 'for' loop to change a canvas everytime the loop executes.
12 Answers
+ 5
... and if you want to improve the code:
var count = 0;
var button_ref;
function example(button) {
if (button) {
button.disabled = true; // disable the button while animation is running
button_ref = button; // save the button reference
}
console.log(count);
if (++count<50) setTimeout(example,500);
else {
count = 0; // reinitialize the counter for being able to rerun the loop
button_ref.disabled = false; // enable the button click
}
}
... and change the onclick attribute of the button with:
onclick = "example(this)"
+ 4
Because you call the setInterval() many times (at each iteration of your for loop)...
Don't use 'for' loop, and if you need a counter use it like:
var count = 0;
function example(){
console.log(count);
if (++count<50) setTimeout(example,500);
}
+ 3
// basically:
var delay = 1000; // milliseconds
function animationLoop() {
/* put here the code used to update canvas */
document.body.innerHTML += 'update<br>'; // just for the demo ;)
/* this last line below call the first argument function after delay */
window.setTimeout(animationLoop,delay);
}
animationLoop(); // call the update function only a first time to start the loop (no 'for' loop)
+ 3
In the setTimeout method, put only the function name: the parameter expect a function object/reference, not the return value of a function call ^^
+ 1
+ 1
Thank you
+ 1
Thanx, I'll definitely try it
0
Francois Breedt What do you mean by sleep function?
0
The program should wait a certain amount of milliseconds before the next line of code executes
0
You can use setTimeout() to execute a function only once after specified time in milliseconds
0
Thank you very much for your help. Can someone please explain why the following does not work
https://code.sololearn.com/WtLHh1rtV1Vg/?ref=app