Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  180] [ 6]  / answers: 1 / hits: 182301  / 11 Years ago, fri, march 29, 2013, 12:00:00

I want to create a JavaScript wait() function.



What should I edit?



function wait(waitsecs) {
setTimeout(donothing(), 'waitsecs');
}

function donothing() {
//
}


More From » function

 Answers
17

Javascript isn't threaded, so a wait would freeze the entire page (and probably cause the browser to stop running the script entirely).



To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:



console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');


But that won't stop execution; after will be logged before your function runs.



To wait properly, you can use anonymous functions:



console.log('before');
setTimeout(function(){
console.log('after');
},500);


All your variables will still be there in the after section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.


[#79253] Thursday, March 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;