Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript wait() function [closed]

I want to create a JavaScript wait() function.

What should I edit?

function wait(waitsecs) {     setTimeout(donothing(), 'waitsecs'); }  function donothing() {     // }  
like image 746
eds1999 Avatar asked Mar 29 '13 00:03

eds1999


People also ask

Does JavaScript wait for function to finish?

JavaScript code execution is asynchronous by default, which means that JavaScript won't wait for a function to finish before executing the code below it.

Is there a sleep function in JavaScript?

Unfortunately, there is no sleep function like that in JavaScript . If you run test2, you will see 'hi' right away ( setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

How do you pause a JavaScript function?

Sleep() With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and Php we would call sleep(sec).


2 Answers

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.

like image 54
Dave Avatar answered Sep 30 '22 07:09

Dave


You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

like image 25
Niet the Dark Absol Avatar answered Sep 30 '22 07:09

Niet the Dark Absol