简体   繁体   中英

Show alert box every X seconds, but wait Y seconds first

I try to show an alert box every X seconds, but it should first wait Y seconds before starting.

I tried it like this, but this will only show the alert box once.

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

Can someone explain why it does not work as expected?

The show_alert("hello") calls a function as you've told once because you're directly calling it . Instead you need to provide a function which passes the behavior , so, in your case which is calling your function. See:

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

Additionally, it calls your function only after X + Y. If you want to run it after X only you need to call it once when you run interval, see:

 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); } 

Because you are calling the function with the first alert, making it pass undefined as the handler function every consecutive time. bind the param to the function instead.

var X = 2000;
var Y = 5000;

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

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

使用bind调用函数。

setInterval(show_alert.bind(null, 'hello'), X);

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