简体   繁体   中英

setInterval executes functions only by the time of the interval ends

I have the next setInterval in JS which emits the test() function only by the time the 5s ends:

let interval = setInterval(() => {
  test()
}, 5000)


function test() {
  console.log("Test") // will be emitted only in 5s
}

How can I tell the method to run the test() function without waiting?

If I understand you right, you want the function to be executed immediately, and then every 5 seconds after that. In which case, just call it initially too.

let interval = setInterval(() => test(), 5000)
test();
test(); //call initially and then after 5 sec
let intervalS = setInterval(() => {
  test()
}, 5000)


function test() {
  console.log("Test") // will be emitted only in 5s
}

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