JavaScript中只能有一个超时

Can there only be one timeout in JavaScript?

本文关键字:有一个 超时 JavaScript      更新时间:2023-09-26

此代码似乎不起作用。。。很长一段时间后,它只显示twCharCount元素一次。可能只有一个超时设置吗?有什么建议可以让这个代码变得更好?谢谢你的建议。。。

var timer = new Array();
var t=0;
var step=1000;
counter.hide();
var t =+ step;
timer[0] = setTimeout("$('#twCharCount').show()",t);
var t =+ step;
timer[1] = setTimeout("$('#twCharCount').hide()",t);
var t =+ step;
timer[2] = setTimeout("$('#twCharCount').show()",t);
var t =+ step;
timer[3] = setTimeout("$('#twCharCount').hide()",t);
var t =+ step;
timer[4] = setTimeout("$('#twCharCount').show()",t);

好的。。对不起。。。写这篇文章的时候我有点不清醒。。。当然,我一直在重新定义。。。这就是为什么所有的执行都很缓慢。。。

var intervalId = window.setInterval(function() {
    $('#twCharCount').toggle();
}, 1000);

并且停止闪烁CCD_ 1。

可能只是一些语法问题:

var timer = [];
var t=0;
var step=1000;
counter.hide();
t += step;
timer[0] = setTimeout("$('#twCharCount').show()", t);
t += step;
timer[1] = setTimeout("$('#twCharCount').hide()", t);
t += step;
timer[2] = setTimeout("$('#twCharCount').show()", t);
t += step;
timer[3] = setTimeout("$('#twCharCount').hide()", t);
t += step;
timer[4] = setTimeout("$('#twCharCount').show()", t);

t =+step;应为t += step;

你不应该一次又一次地重新申报。

代码在很多方面都是错误的:(.
所有函数都在同一时间被调用,因为它们的时间(t(是相同的。

如果您想增加t,您可能不应该在每个访问上声明它(只使用var t = ...一次;之后您可以使用它的名称:t = ...来访问它(,您可能应该使用+=而不是=+:
a += bwindow.clearInterval(intervalId);0的快捷方式,而a =+ ba = parseInt(b)的快捷方式
你可能想写:

var timer = [];
var t=0;
var step=1000;
counter.hide();
t += step;
timer[0] = setTimeout("$('#twCharCount').show()", t);
t += step;
timer[1] = setTimeout("$('#twCharCount').hide()", t);
t += step;
timer[2] = setTimeout("$('#twCharCount').show()", t);
t += step;
timer[3] = setTimeout("$('#twCharCount').hide()", t);
t += step;
timer[4] = setTimeout("$('#twCharCount').show()", t);

还有一点,传递一个函数比传递字符串作为setTimeout函数的第一个参数要好:

setTimeout(function(){$('#twCharCount').show();},t);

Sry,但我忍不住了,这是为你优化的代码:

var timer = [],
step = 1000,
n = 4,
el = $('#twChartCount');
for(var i=0;i<n;i++)
    if(i%2)
        timer[i] = setTimeout(function(){el.hide();},i*step);
    else
        timer[i] = setTimeout(function(){el.show()},i*step);

活动超时的数量实际上没有限制。

我看不出你的代码有任何真正的问题。可能问题不在于超时,而在于您正在执行的命令。

附加说明(与您的问题无关,但值得一提(:

  • 每个函数只需要一次变量的"var"语句
  • 在这种情况下,我会使用timer.push((而不是timer[…]
  • 可以使用单个setInterval((
var show = false;
window.setInterval(function() {
   if(show)
   {
      show = false;
      $('#twCharCount').show();
   }
   else
   {
      show = true;
      $('#twCharCount').hide();
   }
}, 1000);
相关文章: