简体   繁体   中英

Clear an interval after a certain time limit in JavaScript

I'm trying to stop this JavaScript function after 5 seconds.

Here is the code :

<p id="para"></p>

var niceThings = ["You're cool", "You're smart", "You're good looking", "You're a baus", "You're a cool cat."];
var i =0;

function compliment () {

    document.getElementById("para").innerHTML = niceThings[i];

    if(i < niceThings.length-1) {
        i++;    
    }
    else {
        i=0;    
    }
}

window.onload = setInterval(compliment, 500);

I'm sure there's a way to use the setTimeout method somewhere, but I'm a newb. Any thoughts?

setInterval returns a token which can be passed to clearInterval after 5 seconds to stop the silly function in its tracks.

Also, note that you can simplify your array-looping logic using the modulo ( % ) operator.

 var niceThings = [ "You're cool", "You're smart", "You're good looking", "You're a baus", "You're a cool cat." ] var p = document.getElementById("para") var i = 0 function compliment () { p.textContent = niceThings[i] i = (i + 1) % niceThings.length } setTimeout(clearInterval, 5000, setInterval(compliment, 500) ) 
 <p id="para"></p> 

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