Laura
Laura

Reputation: 1

Stop execute javascript until onclick

I'm looking for a method that stop excute a javascript until a onclick.

This is my script, but i don't know how to wait until a onclick.

<html>
<head>
<script type="text/javascript">

var stat = "*";

function setstat(but)  {
    stat = but;
}

function start() {
    alert('start');
    ...
    ...
    /* ??????? wait until stat != '*' ???????? */
    alert(stat);
    ...
    ...
}   
</script>

</head>
<body>
<input type='button' style="width: 100px;" value="Start" onclick="start();">
<br><br>
<input type='button' style="width: 100px;" value="Yes" onclick="setstat('yes')"> 
&nbsp;&nbsp;
<input type='button' style="width: 100px;"` ``value="No" onclick="setstat('no')">`
</body>
</html>

Upvotes: 0

Views: 1599

Answers (3)

angabriel
angabriel

Reputation: 5028

You have to "think" in events. It looks like you want to execute the code at some point in the start function, when the stat is set to 'yes' or 'no'.

Every button onclick is calling a function, more precisely it actually expects a statement. Why not refactor your code and do that stuff when you press the yes button?

To make my point clear:

var stat = '*';

function start() {
  // code

  //until stat != '*';

  // move this code here -->
}

function setstat(but)  {
  stat = but;
  doReallyStart();
}

function doReallyStart() {
  // to here <--
}

This would do the same and is more readable.

Upvotes: 1

Silviu Burcea
Silviu Burcea

Reputation: 5348

var execute = false;
var timeoutPolling = 1000;
var fn = function() {
  console.log('Hello');
};
var it = setInterval(function() {
  if (execute) {
    fn();
    clearInterval(it);
  }
}, timeoutPolling);

This worked in my Chrome Dev Tools, you just have to enable/disable the execute flag.

Upvotes: 0

lwfshensi
lwfshensi

Reputation: 1

Maybe setTimeout and clearTimeout could satisfy your situation. you could put your js code in setTimeout,onClick event trigger clearTimeout

Upvotes: 0

Related Questions