简体   繁体   English

避免在间隔开始时执行setInterval()

[英]Avoid setInterval() executing at start of interval

I've noticed that the setInterval() function actually runs (as in, takes in the values) at the beginning of the interval, then waits and returns the result at the end of the interval. 我注意到setInterval()函数实际上是在间隔开始时运行(例如,取值),然后等待并在间隔结束时返回结果。 If the values change mid-interval, it's still going to execute as it would have had in the beginning. 如果值在间隔中间更改,它仍将像开始时一样执行。 This is causing unwanted behavior in my slider. 这会导致我的滑块出现不良行为。 Is there a way to force setInterval() to do both at the very end of the interval? 有没有一种方法可以强制setInterval()在间隔结束时同时执行这两项操作? Preferably without jQuery. 最好没有jQuery。

EDIT: While I was converting my code to post here, the issue resolved itself. 编辑:当我将代码转换为在此处发布时,问题自行解决。 Turns out it had little to do with my question. 原来,这与我的问题无关。 I'm sorry, I'll be sure to post code next time. 抱歉,下次一定可以发布代码。 THANK YOU FOR THE ANSWERS! 谢谢您的答复! :) Hopefully they help someone in the future, as I couldn't find a question like this anyway. :)希望他们将来能对某人有所帮助,因为无论如何我都找不到这样的问题。

Yes. 是。 Use setTimeout recursively, which is generally better idea. 递归使用setTimeout,这通常是更好的主意。

 function doSomething() { setTimeout(function () { console.log('something') doSomething() }, 2000) } console.log('start') doSomething() 

You should post some of your code. 您应该发布一些代码。 I'm not totally sure if this is your problem, but if you look at this: 我不确定这是否是您的问题,但是如果您查看以下内容:

setInterval(() => {
  var message = 'ok';
  console.log(message);
}, 1000);

message = 'not ok';

The 'message' variable defined inside of setInterval is scoped to the function being passed into setInterval. 在setInterval内部定义的'message'变量的作用域是传递给setInterval的函数。 So when I attempt to change the variable outside of that scope, it won't work. 因此,当我尝试在该范围之外更改变量时,它将不起作用。 I'm actually accidentally creating a new variable on the window object. 我实际上是在窗口对象上意外地创建了一个新变量。

However, if I do this: 但是,如果我这样做:

var message = 'ok';

setInterval(() => {
  console.log(message);
}, 1000);

message = 'not ok';

The 'message' variable is successfully changed and setInterval will call the variable with that change. 成功更改了'message'变量,setInterval将通过该更改调用该变量。

You can bind the variables you need on the window object. 您可以在window对象上绑定所需的变量。

window.myVariable = 'Important String';

setInterval(function() {
  doSomethingWith(window.myVariable);
}, 2000);

// Variable is changed
window.myVariable = 'Less Important String';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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