简体   繁体   中英

What is a better and more efficient way to do this blocking of a function?

var x = 2;

setInterval(function() {
    while(z){}; //do nothing if z = 1, therefor stalling and blocking the next steps:
    change(x++);
    if (x > 39) x = 1;
}, 7000);

Somewhere else in program: A button is pause button pressed, toggling (xor-ing) z to either 1 or 0 to block the interval function. Otherwise if z == 0, skip this.

I am aware for a number of reasons this is inefficient and bad programming and can cause problems in JS but want to do something that accomplishes the same thing. I am a strong C programmer but javascript is brand new to me and none of my C approaches to this problem seem to be within my javascript abilities here. I basically am trying to pause the interval function when a pause button is pressed.

EDIT: The change() function is long and doesn't really matter, it could be an arbitrary set of instructions, thanks for the response

It would be better to store interval id

var x = 2;

var intervalID = setInterval(function() {
    change(x++);
    if (x > 39) x = 1;
}, 1000);

and when the pause button is pressed - use clearInterval to implement pause

clearInterval(intervalID);

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM