每隔X秒显示警报框,但先等待Y秒

时间:2016-03-29 08:13:10

标签: javascript

我尝试每隔X秒显示一个警告框,但它应该在开始之前等待Y秒。

我试过这样,但这只会显示一次警告框。

var X = 2000;
var Y = 5000;

setTimeout(function(){
        var IntervalID = setInterval(show_alert("hello"), X);
    }, 
Y);

function show_alert(str)
{
  alert(str);
}  

有人可以解释为什么它不能按预期工作吗?

3 个答案:

答案 0 :(得分:2)

show_alert("hello")会调用一个函数,因为您已经直接调用它。相反,你需要提供一个传递behavior的函数,因此,在你调用函数的情况下。参见:



var X = 2000;
var Y = 5000;

setTimeout
(
  function()
  {
    var IntervalID = setInterval(function() { show_alert("hello") }, X);
  },
  Y
);

function show_alert(str)
{
  alert(str);
}  




此外,它仅在X + Y之后调​​用您的函数。如果您想在X之后运行它,只需要在运行间隔时调用它一次,请参阅:



var X = 2000;
var Y = 5000;

setTimeout
(
  function()
  {
    var IntervalID = setInterval(function() { show_alert("hello") }, X);

    show_alert("hello");
  },
  Y
);

function show_alert(str)
{
  alert(str);
}  




答案 1 :(得分:1)

因为您使用第一个警报调用该函数,所以每次连续都将undefined作为处理函数传递。 bind代替函数的参数。

var X = 2000;
var Y = 5000;

setTimeout
(
  function()
  {
    var IntervalID = setInterval(show_alert.bind(null, 'hello'), X);
  },
  Y
);

function show_alert(str)
{
  alert(str);
} 

答案 2 :(得分:0)

使用bind调用函数。

setInterval(show_alert.bind(null, 'hello'), X);
相关问题