confusion over setTimeout and clearTimeout

前端 未结 3 1346
春和景丽
春和景丽 2020-12-22 05:09

I have a button that changes the background of a div when its rolled over. the background needs to change on a timer so i have used setTimout to execute methods that change

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-22 06:11

    When you call setTimeout, it returns a numeric value. You should store this value, because this is what you need for clearTimeout. So keep track of the return value from both setTimeout's (they will be different). And keep track of them in a scope you can access from both functions.

    Quick 'n' Dirty Example:

    var timer = setTimeout( function(){ alert('hi'); }, 300 );
    clearTimeout( timer );
    

    Also, you are calling setTimeout with 'playV()', this is incorrect as it will immediately call that function this way. You can leave the brackets behind, so just setTimeout( playV, 3500 );

提交回复
热议问题