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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

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;

lukas.pukenis
  • 13,057
  • 12
  • 47
  • 81
  • 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.. :) – Saurav Deb Purkayastha Jul 19 '12 at 15:04
  • 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 :) – lukas.pukenis Jul 19 '12 at 15:49
  • 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. – Saurav Deb Purkayastha Jul 19 '12 at 16:09
0

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

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
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

Liran H
  • 9,143
  • 7
  • 39
  • 52