[英]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. 程序中的其他位置:按下暂停按钮,将z切换(异或)到1或0以阻止间隔功能。 Otherwise if z == 0, skip this.
否则,如果z == 0,则跳过此步骤。
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. 我知道,由于多种原因,这效率低下且编程错误,可能会导致JS问题,但希望做一些能完成相同任务的事情。 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.
我是一名强大的C程序员,但是javascript对我来说是全新的,解决这个问题的C语言方法似乎都不在我的javascript能力范围内。 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 编辑:change()函数很长,并不重要,它可以是任意指令集,感谢您的回应
It would be better to store interval id 最好存储间隔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实现暂停
clearInterval(intervalID);
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval https://developer.mozilla.org/zh-CN/docs/Web/API/WindowTimers/clearInterval
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.