Is there any way to suspend a js script until some event like a mouse click on a button occurs?? I mean the script should pause its execution and resume again when the event occurs. I am kind of new to Javascript and even after a thorough search on the net couldn't find a solution!!
-
have a look this thread ,stackoverflow.com/questions/951021/javascript-sleep. might you want to refactorindiPy– indiPy2012-07-19 14:43:50 +00:00Commented Jul 19, 2012 at 14:43
-
um call the function on the click of the button to start it up?epascarello– epascarello2012-07-19 14:51:25 +00:00Commented Jul 19, 2012 at 14:51
Add a comment
|
3 Answers
JS is single threaded and multithreading can be done us Web Workers only. As far as I know.
However if you have only a little script which you want to suspend, you can have a global variable/flag and simply in your script(I somehow believe it's a loop or event driven function) have a check for that flag. In this case:
var flag = false;
...
if (flag) {
do your code
} else {
do nothing or return if in function
}
Once you want to continue, just set flag = true;
3 Comments
Saurav Deb Purkayastha
Okay.. Thank you.. Actually what i wanted to do is create a custom alert box which returns a value based on what button was clicked just like the default js alert box. I was kind of reluctant to use global variables to do this, but looks like I have got no other immediate choice. Anyways thank you for solution.. :)
lukas.pukenis
NP. You can use setTimeout() in case your script is in a loop. Using infinite checking causes the CPU go to 99% usage, so you can consider using setTimeout on your checking function to see if the flag has changed :)
Saurav Deb Purkayastha
I found a way to implement this alert box finally in a proper manner.. I simply added a callback function to my alert box function. As soon as any button is clicked in the alert box the function is called with the id of the button that was clicked.
If what you are trying to pause is a function which would otherwise keep looping, I've come up with a good solution: https://stackoverflow.com/a/47841425/2884291