0

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!!

2

3 Answers 3

1

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;

Sign up to request clarification or add additional context in comments.

3 Comments

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.. :)
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 :)
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.
0

JavaScript is single threaded with no preemption when events occur. It's not possible.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.