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.

8th Dec 2018, 8:19 PM
Francois Breedt
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)"
8th Dec 2018, 9:23 PM
visph
visph - avatar
+ 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); }
8th Dec 2018, 9:07 PM
visph
visph - avatar
+ 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)
8th Dec 2018, 8:57 PM
visph
visph - avatar
+ 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 ^^
8th Dec 2018, 9:32 PM
visph
visph - avatar
8th Dec 2018, 8:53 PM
BroFar
BroFar - avatar
+ 1
Thank you
8th Dec 2018, 9:12 PM
Francois Breedt
+ 1
Thanx, I'll definitely try it
8th Dec 2018, 9:27 PM
Francois Breedt
0
Francois Breedt What do you mean by sleep function?
8th Dec 2018, 8:32 PM
Dlite
Dlite - avatar
0
The program should wait a certain amount of milliseconds before the next line of code executes
8th Dec 2018, 8:48 PM
Francois Breedt
0
You can use setTimeout() to execute a function only once after specified time in milliseconds
8th Dec 2018, 8:52 PM
Rishi Anand
Rishi Anand - avatar
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
8th Dec 2018, 9:01 PM
Francois Breedt